import type { Metadata } from "next";
import Link from "next/link";
import { ScrollText } from "lucide-react";
import { getGeneralSettings } from "@/lib/settings";
import { commonTexts } from "@/lib/i18n/common";
import { affiliatesTexts } from "@/lib/i18n/affiliates";
import { PublicNavbar } from "@/components/public/navbar";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Terms of Service — SMM Panel",
  description:
    "The terms that govern accounts, orders, deposits, refunds and API access on this SMM panel.",
};

const texts = affiliatesTexts.terms;
const LAST_UPDATED = "24 August 2026";

type Section = {
  id: string;
  title: string;
  paragraphs?: string[];
  bullets?: string[];
};

function buildSections(panel: string): Section[] {
  return [
    {
      id: "acceptance",
      title: "1. Acceptance of these terms",
      paragraphs: [
        `These Terms of Service ("Terms") form a binding agreement between you and ${panel} ("we", "us", "the panel"). By creating an account, placing an order, depositing funds or calling our API you confirm that you have read these Terms and agree to be bound by them.`,
        "If you do not agree with any part of these Terms, do not use the panel. Continuing to use your account after a change to these Terms means you accept the updated version.",
      ],
    },
    {
      id: "service",
      title: "2. What the panel is",
      paragraphs: [
        `${panel} is a reseller marketplace for social media marketing services. We list services such as followers, likes, views, subscribers, comments and mentions, we take your order, and we forward it to the supplier network that actually performs the delivery.`,
        "We are an intermediary. We do not host, own or operate any social network, and we do not perform the delivery ourselves.",
      ],
    },
    {
      id: "no-affiliation",
      title: "3. No affiliation with social platforms",
      paragraphs: [
        "We are not affiliated with, endorsed by, sponsored by or in any way officially connected to Instagram, TikTok, YouTube, Facebook, Telegram, X/Twitter or any other platform named on this site. All product names, logos and brands are the property of their respective owners and are used for identification only.",
        "Using third-party growth services may conflict with the terms of the platform you are promoting. You are solely responsible for deciding whether to use these services on your accounts and for any consequence the platform applies to them, including rate limiting, shadow-banning, content removal or account suspension.",
      ],
    },
    {
      id: "accounts",
      title: "4. Accounts",
      paragraphs: [
        "You must be at least 18 years old, or the age of majority where you live, to hold an account. One person or business may hold one account unless we agree otherwise in writing.",
      ],
      bullets: [
        "Provide accurate registration details and keep your email address current — it is how we reach you about orders, payments and security.",
        "You are responsible for everything that happens under your account, including orders placed with your API key.",
        "Keep your password and API key secret. Rotate your API key immediately if you suspect it has leaked.",
        "Creating multiple accounts to abuse promotions, bonuses, referral commissions or refunds is prohibited and may lead to all affected accounts being suspended.",
      ],
    },
    {
      id: "orders",
      title: "5. Orders and pricing",
      paragraphs: [
        "Every service shows its rate per 1000 units (or a fixed package price), the minimum and maximum quantity, and an average delivery time. The charge for a standard order is quantity ÷ 1000 × rate. Package services are charged at the package price. Drip-feed orders are charged for every run up front: quantity × runs ÷ 1000 × rate.",
        "The charge is deducted from your panel balance the moment the order is created, before it reaches the supplier. Prices and service availability can change at any time; the price shown at the moment you submit is the price you pay for that order.",
      ],
      bullets: [
        "Send the exact link format the service expects. A wrong, private or deleted link is the most common cause of a failed order and is not our responsibility.",
        "Do not change your username, switch your profile to private or delete the target post while an order is running — the supplier cannot finish and the order may be marked partial or failed without a refund.",
        "Some services block a second live order for the same link. Wait for the first one to complete.",
        "Placing the same order through several panels at once can cause overlapping deliveries; we cannot separate results in that case.",
      ],
    },
    {
      id: "deposits",
      title: "6. Deposits and balance",
      paragraphs: [
        "Funds added to your account are stored as panel balance and can only be used to buy services on this panel. Manual and bank deposits are created as pending and are credited once an administrator confirms the payment; automated methods credit once the payment provider confirms settlement.",
        "Deposit bonuses, where offered, are credited as a separate bonus transaction and follow the conditions shown on the Add funds page at the time of the deposit.",
      ],
      bullets: [
        "Balance is not a bank deposit, earns no interest and has no cash value outside this panel.",
        "Credited balance is not withdrawable to your original payment method or to any other account.",
        "You must be the lawful owner of the payment method used. Chargebacks or payment disputes filed instead of contacting support will result in immediate suspension and cancellation of the remaining balance.",
        "Deposits sent to the wrong address, network or memo cannot be recovered.",
      ],
    },
    {
      id: "delivery",
      title: "7. Delivery, drip-feed and subscriptions",
      paragraphs: [
        "Average time is an estimate based on recent orders, not a guarantee. Supplier queues, platform-side rate limits and account restrictions can slow delivery. An order is not considered late until it has clearly exceeded the stated average time by a wide margin, and support will check with the supplier before taking action.",
        "Drip-feed spreads a delivery across a number of runs at a fixed interval. Subscriptions watch an account and order automatically on new posts, within the minimum and maximum quantity you set, until the number of posts is exhausted or the expiry date is reached. Cancelling a drip-feed refunds the runs that have not started.",
      ],
    },
    {
      id: "refills",
      title: "8. Refills",
      paragraphs: [
        "Services marked as refillable include a refill window, shown on the service. If the delivered count drops inside that window you can request a refill from the order list and we will forward the request to the supplier.",
      ],
      bullets: [
        "A refill tops the order back up; it is not a substitute for a refund and does not extend the original guarantee.",
        "Refill requests outside the window, on non-refillable services, or on orders whose link has changed are rejected.",
        "One refill request can be open per order at a time.",
      ],
    },
    {
      id: "refunds",
      title: "9. Cancellations and refunds",
      paragraphs: [
        "Refunds are always issued as panel balance, never as a payment back to your card, bank or wallet. Our refund logic follows exactly what the panel records for the order:",
      ],
      bullets: [
        "Canceled — the full charge is returned to your balance.",
        "Partial — the undelivered part is returned automatically, calculated as remaining quantity ÷ ordered quantity × charge.",
        "Failed or errored before dispatch — the full charge is returned once the order is closed.",
        "Completed — no refund. A completed order that later loses units is handled through the refill process, where the service supports it.",
        "Cancellation is only possible while the order has not been delivered and only on services marked as cancellable. Requesting cancellation is a request to the supplier, not a guarantee.",
      ],
    },
    {
      id: "prohibited",
      title: "10. Prohibited use",
      paragraphs: [
        "You may not use the panel to promote or amplify content that is illegal, that sexualises minors, that incites violence or hatred, that impersonates another person or organisation, that distributes malware, or that is part of a fraud, phishing or investment scam.",
        "You may not resell access to another person's account, attempt to bypass rate limits, scrape the panel, probe our infrastructure for vulnerabilities, or use automated tools to place orders in a way that degrades service for other customers.",
      ],
    },
    {
      id: "affiliate",
      title: "11. Affiliate programme",
      paragraphs: [
        "Registered users receive a referral link. When someone signs up through your link and completes a deposit, a commission at the rate shown on your Affiliates page is credited to your available earnings.",
      ],
      bullets: [
        "Referrals are attributed through a cookie that lasts 30 days and are then stored permanently on the referred account.",
        "You may request a payout once your available earnings reach the published minimum. Every payout is reviewed by an administrator before it is approved.",
        "Approved payouts are credited to your panel balance.",
        "Self-referral, referring accounts you also control, incentivised sign-ups, spam and misleading advertising void the commission and may close your affiliate account.",
      ],
    },
    {
      id: "api",
      title: "12. API access",
      paragraphs: [
        "Our API v2 lets you place and track orders programmatically with your personal API key. You are responsible for every request signed with your key, including requests made by software you deploy or by third parties you share the key with.",
      ],
      bullets: [
        "Requests are rate limited per key. Sustained abuse of the limit may lead to the key being revoked.",
        "Never retry a timed-out order request automatically — check the order status first, otherwise you may create a duplicate order that is charged twice.",
        "Rates returned by the API are your personal rates and must not be published as ours.",
      ],
    },
    {
      id: "suspension",
      title: "13. Suspension and termination",
      paragraphs: [
        "We may suspend or close an account that breaches these Terms, that shows signs of fraud or payment abuse, or that we are required to act against by law. Where a suspension is our error or the breach is minor and corrected, we restore access and any balance.",
        "You may stop using the panel at any time. Ask support to close your account; any remaining balance may be used for orders before the account is closed, but it cannot be paid out.",
      ],
    },
    {
      id: "availability",
      title: "14. Availability and changes to services",
      paragraphs: [
        "We work to keep the panel available at all times but do not promise uninterrupted service. Maintenance, supplier outages and platform-side changes can make individual services slow, temporarily unavailable or permanently withdrawn. When a service is withdrawn, orders that have not been dispatched are refunded to balance.",
      ],
    },
    {
      id: "liability",
      title: "15. Limitation of liability",
      paragraphs: [
        "To the maximum extent permitted by law, our total liability for any claim connected to your use of the panel is limited to the amount you paid for the specific order that gave rise to the claim. We are not liable for indirect or consequential loss, including lost profit, lost audience, loss of reputation or action taken against your account by a social platform.",
        "Nothing in these Terms excludes liability that cannot lawfully be excluded.",
      ],
    },
    {
      id: "privacy",
      title: "16. Data and privacy",
      paragraphs: [
        "We store the data needed to run your account: registration details, order and payment history, sign-in records including IP address and browser user agent, and support conversations. Sign-in records and payment metadata are also used to detect fraud.",
        "Links and usernames you submit are shared with the supplier that fulfils the order, because delivery is impossible otherwise. We do not sell your data. We never ask for your social account password and you should never send it to us.",
      ],
    },
    {
      id: "support",
      title: "17. Support",
      paragraphs: [
        "Support runs through the ticket system inside the panel, so every conversation stays attached to your account and orders. Include the order ID and a short description of the problem; screenshots help. We answer tickets in the order they arrive.",
      ],
    },
    {
      id: "changes",
      title: "18. Changes to these Terms",
      paragraphs: [
        "We may update these Terms as the panel, our suppliers or the law change. The revision date at the top of this page always reflects the current version. Material changes are announced inside the panel. Orders are governed by the version of the Terms in force when the order was placed.",
      ],
    },
    {
      id: "law",
      title: "19. Governing law",
      paragraphs: [
        "These Terms are governed by the laws of the jurisdiction in which the panel operator is established, without regard to conflict-of-law rules. Any dispute that cannot be resolved through support will be handled by the competent courts of that jurisdiction.",
      ],
    },
  ];
}

export default async function TermsPage() {
  const general = await getGeneralSettings();
  const panel = general.panelName || commonTexts.appName;
  const sections = buildSections(panel);

  return (
    <div className="min-h-screen bg-background">
      <PublicNavbar />

      <main className="mx-auto w-full max-w-screen-xl px-4 py-10 sm:px-6 lg:px-8 lg:py-14">
        <header className="space-y-3 border-b pb-8">
          <div className="flex items-center gap-2 text-xs font-semibold tracking-wider text-primary uppercase">
            <ScrollText className="size-3.5" />
            {panel}
          </div>
          <h1 className="font-display text-3xl font-semibold tracking-tight sm:text-4xl">
            {texts.title}
          </h1>
          <p className="max-w-2xl text-sm text-muted-foreground sm:text-base">{texts.subtitle}</p>
          <p className="font-mono text-xs text-muted-foreground">
            {texts.lastUpdated}: {LAST_UPDATED}
          </p>
        </header>

        <div className="mt-10 grid gap-10 lg:grid-cols-[220px_minmax(0,1fr)] lg:gap-14">
          <nav className="lg:sticky lg:top-8 lg:self-start">
            <p className="mb-3 text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
              {texts.tocTitle}
            </p>
            <ul className="space-y-1.5 text-sm">
              {sections.map((section) => (
                <li key={section.id}>
                  <a
                    href={`#${section.id}`}
                    className="text-muted-foreground transition-colors hover:text-primary"
                  >
                    {section.title}
                  </a>
                </li>
              ))}
            </ul>
          </nav>

          <article className="max-w-3xl space-y-10">
            {sections.map((section) => (
              <section key={section.id} id={section.id} className="scroll-mt-24 space-y-3">
                <h2 className="font-display text-xl font-semibold tracking-tight">
                  {section.title}
                </h2>
                {section.paragraphs?.map((paragraph) => (
                  <p key={paragraph.slice(0, 40)} className="text-sm leading-relaxed text-muted-foreground">
                    {paragraph}
                  </p>
                ))}
                {section.bullets ? (
                  <ul className="space-y-2 pl-1">
                    {section.bullets.map((bullet) => (
                      <li
                        key={bullet.slice(0, 40)}
                        className="flex gap-2.5 text-sm leading-relaxed text-muted-foreground"
                      >
                        <span className="mt-2 size-1.5 shrink-0 rounded-full bg-primary/50" />
                        <span>{bullet}</span>
                      </li>
                    ))}
                  </ul>
                ) : null}
              </section>
            ))}

            <div className="rounded-2xl border bg-muted/30 p-5 text-sm text-muted-foreground">
              Questions about these Terms? Open a ticket from the{" "}
              <Link href="/tickets" className="font-medium text-primary hover:underline">
                support area
              </Link>{" "}
              of the panel, or read the{" "}
              <Link href="/api" className="font-medium text-primary hover:underline">
                API documentation
              </Link>{" "}
              if your question is about automated ordering.
            </div>
          </article>
        </div>
      </main>
    </div>
  );
}
