// =============================================================
// Design Brains — Legal pages (Privacy, Terms, Cookies)
// =============================================================

const LEGAL_LAST_UPDATED = "May 04, 2026";

const LEGAL_PAGES = {
  privacy: {
    eyebrow: "LEGAL · PRIVACY",
    title: "Privacy Policy",
    subtitle: "What we collect, why we collect it, and the controls you have over it. We try to keep this short and human-readable.",
    sections: [
      {
        id: "summary",
        h: "The short version",
        body: [
          "We collect the minimum we need to run our business and serve our clients. We don't sell your data, ever. We don't run third-party advertising trackers on this website.",
          "If you've worked with us, the data we hold about you is the same kind any agency would: contact details, project files, invoices, and the messages we've exchanged. If you've only browsed the site, we hold almost nothing.",
        ],
      },
      {
        id: "collected",
        h: "What we collect",
        body: [
          "Information you give us — your name, email, company, phone number, project details, and anything you share in a quote form, message, or call.",
          "Information collected automatically — IP address, device and browser type, pages visited, and approximate location (country and city). We use a self-hosted, cookie-light analytics tool for this.",
          "Information from clients — files, content, credentials, and other materials shared with us during an engagement. We treat all of it as confidential.",
        ],
      },
      {
        id: "use",
        h: "How we use it",
        body: [
          "To respond to enquiries and prepare quotes.",
          "To deliver the work you've engaged us for, including communicating, sharing drafts, and managing access to staging environments.",
          "To send invoices, manage payments, and meet our tax and legal obligations.",
          "To improve the website and understand which content is useful — in aggregate, never individually.",
        ],
      },
      {
        id: "sharing",
        h: "Who we share it with",
        body: [
          "Only with vendors who help us run the business — payment processors, hosting providers, email and accounting tools. Each is bound by their own privacy and security commitments.",
          "When required by law, regulation, or a valid legal request from authorities in Bangladesh or the country where the data subject resides.",
          "Never with advertisers, data brokers, or anyone who wants to retarget you.",
        ],
      },
      {
        id: "retention",
        h: "How long we keep it",
        body: [
          "Project files: for 24 months after project close, then archived. After 5 years they're permanently deleted unless you ask us to extend.",
          "Invoicing and tax records: 7 years, as required by Bangladesh tax law.",
          "Marketing and contact records: until you ask us to delete them, or 24 months of inactivity — whichever comes first.",
        ],
      },
      {
        id: "rights",
        h: "Your rights",
        body: [
          "You can ask us what data we hold about you, request a copy, ask us to correct it, or ask us to delete it. We'll respond within 30 days.",
          "If you're in the EU, UK, or California, you have additional rights under GDPR, UK-GDPR, and CCPA — including the right to object to processing and to data portability. We honor all of them globally as a default.",
          "Email privacy@designbrains.co with any request. We don't require a fancy form — a clear sentence is enough.",
        ],
      },
      {
        id: "security",
        h: "Security",
        body: [
          "All client data is encrypted in transit (TLS 1.2+) and at rest. Production credentials sit in a password manager with hardware-key 2FA on every team account.",
          "We follow the principle of least privilege — only the people on your project have access to your project. Access is reviewed at every project close.",
          "If we ever suffer a breach affecting your data, we'll notify you within 72 hours of confirming it, regardless of legal requirement.",
        ],
      },
      {
        id: "children",
        h: "Children",
        body: [
          "Our services are not directed at children under 13. We don't knowingly collect data from anyone in that age range. If you believe we have, please contact us and we'll delete it.",
        ],
      },
      {
        id: "changes-privacy",
        h: "Changes to this policy",
        body: [
          "If we change this policy materially we'll post a notice on this page and email any active clients. The 'Last updated' date at the top always reflects the most recent revision.",
        ],
      },
      {
        id: "contact-privacy",
        h: "Contact",
        body: [
          "Privacy questions go to privacy@designbrains.co. Everything else: hello@designbrains.co.",
          "Mailing address: Design Brains, Bogra Sadar, Bogra 5800, Bangladesh.",
        ],
      },
    ],
  },

  terms: {
    eyebrow: "LEGAL · TERMS",
    title: "Terms of Service",
    subtitle: "The agreement between you and Design Brains when you use this website or engage us for work. Plain language, no surprises.",
    sections: [
      {
        id: "agreement",
        h: "Agreement",
        body: [
          "By using this website you agree to these terms. If you engage us for paid work, the Statement of Work we sign together takes precedence over anything here that conflicts with it.",
          "These terms are governed by the laws of Bangladesh. Any dispute that can't be resolved by a polite email goes to the courts of Bogra.",
        ],
      },
      {
        id: "services",
        h: "What we offer",
        body: [
          "Design Brains provides digital design, web development, mobile app development, and AI automation services. The exact deliverables, timeline, and price for any engagement are defined in a written Statement of Work.",
          "Anything you read on this website — case studies, pricing ranges, blog posts — is informational. It's not a binding offer until we sign a SOW together.",
        ],
      },
      {
        id: "your-responsibilities",
        h: "Your responsibilities",
        body: [
          "Provide content, feedback, and approvals on the schedule we agree to. Most projects that slip do so because feedback rounds drag — we'll flag it early if we see it happening.",
          "Make sure you have the rights to anything you give us — copy, photos, code, brand assets. We'll assume you do.",
          "Pay invoices on time. Late payments past 14 days accrue 1.5% monthly interest, and we may pause work after 30 days.",
        ],
      },
      {
        id: "ip",
        h: "Intellectual property",
        body: [
          "On final payment, all rights to the deliverables we create specifically for your project transfer to you. You own your designs, your code, your content.",
          "We retain rights to our pre-existing tools, libraries, and frameworks — anything we built before your project started. You get a non-exclusive perpetual licence to use any of these embedded in your deliverables.",
          "We may show your project in our portfolio, case studies, and award submissions unless your SOW says otherwise. We never publish anything before your launch.",
        ],
      },
      {
        id: "warranties",
        h: "Warranties",
        body: [
          "We warrant that work we deliver will be performed to professional industry standards and will be free of material defects for 30 days after delivery. We'll fix any defect reported in that window at no charge.",
          "Beyond that, the website and our work are provided 'as is' — we make no other warranties, express or implied.",
        ],
      },
      {
        id: "liability",
        h: "Limitation of liability",
        body: [
          "Our total liability for any claim arising from your use of this website or our services is capped at the fees you paid us in the 12 months before the claim, or USD 1,000 — whichever is greater.",
          "We are not liable for indirect, incidental, or consequential damages — lost profits, data loss, business interruption, and similar — even if we were warned they were possible.",
          "Nothing in these terms excludes liability we can't legally exclude — including for fraud, gross negligence, or death and personal injury caused by us.",
        ],
      },
      {
        id: "indemnification",
        h: "Indemnification",
        body: [
          "You agree to indemnify us against claims arising from content you supply (e.g. copyright disputes about text or images you gave us), and from your use of the deliverables in ways the SOW didn't anticipate.",
          "We agree to indemnify you against claims that our original work infringes a third party's intellectual property — within the liability cap above.",
        ],
      },
      {
        id: "termination",
        h: "Termination",
        body: [
          "Either party may terminate an engagement with 14 days written notice. If you terminate without cause, you pay for work delivered up to the termination date plus a 25% kill fee on the remaining balance.",
          "We may terminate immediately for material breach (non-payment, abuse of our team, or asking us to do something illegal or unethical). We'll always try to resolve it before terminating.",
        ],
      },
      {
        id: "changes-terms",
        h: "Changes to these terms",
        body: [
          "We may update these terms occasionally. The 'Last updated' date at the top reflects the most recent change. Material changes will be emailed to active clients. Continued use of the website constitutes acceptance.",
        ],
      },
      {
        id: "contact-terms",
        h: "Contact",
        body: [
          "Questions about these terms: legal@designbrains.co.",
          "Mailing address: Design Brains, Bogra Sadar, Bogra 5800, Bangladesh.",
        ],
      },
    ],
  },

  cookies: {
    eyebrow: "LEGAL · COOKIES",
    title: "Cookie Policy",
    subtitle: "We use very few cookies — most of them are functional, not tracking. Here's exactly what's running on this website.",
    sections: [
      {
        id: "what-are-cookies",
        h: "What cookies are",
        body: [
          "Cookies are tiny text files a website stores on your device. Some are essential (so logged-in users stay logged in). Others are used for analytics, personalisation, or advertising.",
          "Local storage and session storage are similar mechanisms, used by modern websites for the same kinds of things. We treat them the same way as cookies in this policy.",
        ],
      },
      {
        id: "what-we-use",
        h: "What we use",
        body: [
          "Functional storage — we store your theme preference (light or dark) and quote-builder progress in localStorage so you don't lose them on refresh. No tracking, no personal data.",
          "Analytics — we use a self-hosted, privacy-respecting analytics tool that records aggregate page views without setting any tracking cookies. No fingerprinting, no cross-site identifiers.",
          "Embedded media — if we embed YouTube or Vimeo on a blog post, those services may set their own cookies on play. We use privacy-enhanced embeds where available.",
          "What we don't use — Google Analytics, Meta Pixel, third-party advertising tags, retargeting pixels, session replay tools. None of it.",
        ],
      },
      {
        id: "table",
        h: "Cookie inventory",
        table: {
          head: ["Name", "Purpose", "Expires"],
          rows: [
            ["db-theme", "Stores your light/dark theme preference", "1 year"],
            ["db-quote-state", "Saves your in-progress quote so a refresh doesn't lose it", "30 days"],
            ["plausible_ignore", "Set only if you opt out of analytics", "Indefinite"],
            ["YouTube / Vimeo", "Set by embedded video players on blog posts (only after you press play)", "Varies by provider"],
          ],
        },
      },
      {
        id: "controls",
        h: "Your controls",
        body: [
          "Every modern browser lets you block cookies, clear them, or get a notification before one is set. Look in your browser's privacy settings.",
          "If you want to opt out of our analytics specifically, set the cookie 'plausible_ignore=true' on this domain — or block plausible.io in your network settings.",
          "Blocking functional cookies will mean theme preference and quote progress don't persist. Everything else on the site continues to work.",
        ],
      },
      {
        id: "do-not-track",
        h: "Do Not Track",
        body: [
          "We honor Do Not Track signals. If your browser sends one, we don't record analytics for that session.",
          "We also honor Global Privacy Control (GPC) the same way.",
        ],
      },
      {
        id: "changes-cookies",
        h: "Changes to this policy",
        body: [
          "If we add a new cookie or storage mechanism, we'll update the inventory above and the 'Last updated' date. We'll never quietly add a tracking pixel — that's not the kind of website we run.",
        ],
      },
      {
        id: "contact-cookies",
        h: "Contact",
        body: [
          "Questions about cookies and tracking: privacy@designbrains.co.",
        ],
      },
    ],
  },
};

function LegalPage({ kind }) {
  const data = LEGAL_PAGES[kind];
  const [activeId, setActiveId] = useState(data?.sections?.[0]?.id || "");

  useEffect(() => {
    if (!data) return;
    const ids = data.sections.map((s) => s.id);
    const onScroll = () => {
      let current = ids[0];
      for (const id of ids) {
        const el = document.getElementById(id);
        if (!el) continue;
        const top = el.getBoundingClientRect().top;
        if (top < 160) current = id;
      }
      setActiveId(current);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [kind]);

  if (!data) return <NotFound />;

  const otherKinds = Object.keys(LEGAL_PAGES).filter((k) => k !== kind);

  const scrollToId = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    const y = el.getBoundingClientRect().top + window.scrollY - 110;
    window.scrollTo({ top: y, behavior: "smooth" });
  };

  return (
    <>
      <PageHero eyebrow={data.eyebrow} title={data.title} subtitle={data.subtitle}>
        <div className="font-mono" style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.12em", textTransform: "uppercase" }}>
          Last updated · {LEGAL_LAST_UPDATED}
        </div>
      </PageHero>

      <section style={{ paddingTop: 40, paddingBottom: 120 }}>
        <div className="container">
          <div className="legal-layout" style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 80 }}>
            <aside style={{ position: "sticky", top: 120, alignSelf: "start" }}>
              <div className="font-mono" style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 16 }}>On this page</div>
              <nav style={{ display: "flex", flexDirection: "column", gap: 2, marginBottom: 40 }}>
                {data.sections.map((s) => {
                  const active = activeId === s.id;
                  return (
                    <button
                      key={s.id}
                      onClick={() => scrollToId(s.id)}
                      style={{
                        textAlign: "left",
                        padding: "10px 14px",
                        background: active ? "var(--brand-faint)" : "transparent",
                        border: "1px solid",
                        borderColor: active ? "rgba(108,191,0,0.3)" : "transparent",
                        borderRadius: 10,
                        color: active ? "var(--brand)" : "var(--fg-2)",
                        fontSize: 14,
                        fontWeight: active ? 600 : 400,
                        cursor: "pointer",
                        transition: "all 0.2s var(--ease)",
                      }}
                    >
                      {s.h}
                    </button>
                  );
                })}
              </nav>

              <div className="font-mono" style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 12 }}>Other policies</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {otherKinds.map((k) => (
                  <Link key={k} to={`/${k}`} style={{ fontSize: 14, color: "var(--fg-2)" }}>
                    {LEGAL_PAGES[k].title} →
                  </Link>
                ))}
              </div>
            </aside>

            <div style={{ maxWidth: 720 }}>
              {data.sections.map((s, i) => (
                <Reveal key={s.id} delay={i * 30}>
                  <div id={s.id} style={{ scrollMarginTop: 110, marginBottom: 56 }}>
                    <h2 className="font-display" style={{ fontSize: 28, fontWeight: 600, letterSpacing: "-0.02em", marginBottom: 20 }}>
                      {s.h}
                    </h2>
                    {s.body && s.body.map((p, j) => (
                      <p key={j} style={{ color: "var(--fg-2)", fontSize: 16, lineHeight: 1.65, marginBottom: 14 }}>
                        {p}
                      </p>
                    ))}
                    {s.table && (
                      <div style={{ marginTop: 8, overflowX: "auto", border: "1px solid var(--border)", borderRadius: 12 }}>
                        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 14 }}>
                          <thead>
                            <tr>
                              {s.table.head.map((h) => (
                                <th key={h} className="font-mono" style={{
                                  textAlign: "left", padding: "14px 18px",
                                  fontSize: 11, color: "var(--muted)", letterSpacing: "0.12em", textTransform: "uppercase",
                                  background: "var(--surface)",
                                  borderBottom: "1px solid var(--border)",
                                }}>{h}</th>
                              ))}
                            </tr>
                          </thead>
                          <tbody>
                            {s.table.rows.map((row, ri) => (
                              <tr key={ri}>
                                {row.map((cell, ci) => (
                                  <td key={ci} style={{
                                    padding: "14px 18px",
                                    color: ci === 0 ? "var(--fg)" : "var(--fg-2)",
                                    fontWeight: ci === 0 ? 500 : 400,
                                    borderTop: ri === 0 ? "none" : "1px solid var(--border)",
                                    fontFamily: ci === 0 ? "DM Sans, sans-serif" : undefined,
                                  }}>{cell}</td>
                                ))}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    )}
                  </div>
                </Reveal>
              ))}

              <Reveal>
                <div style={{
                  marginTop: 24, padding: 28,
                  border: "1px solid var(--border)", borderRadius: 16,
                  background: "var(--surface)",
                  display: "flex", justifyContent: "space-between", alignItems: "center",
                  gap: 24, flexWrap: "wrap",
                }}>
                  <div>
                    <div className="font-display" style={{ fontSize: 18, fontWeight: 600, marginBottom: 4 }}>Questions about this?</div>
                    <div style={{ color: "var(--muted)", fontSize: 14 }}>We'd rather hear from you than have you guess.</div>
                  </div>
                  <Link to="/contact" style={{ color: "var(--brand)", fontWeight: 600, fontSize: 15 }}>Contact us →</Link>
                </div>
              </Reveal>
            </div>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 880px) {
          .legal-layout { grid-template-columns: 1fr !important; gap: 32px !important; }
          .legal-layout aside { position: static !important; }
        }
      `}</style>
    </>
  );
}

Object.assign(window, { LegalPage });
