// =============================================================
// Design Brains — FAQ Page
// =============================================================

const FAQ_DATA = [
  {
    cat: "Website Development",
    items: [
      { q: "What stacks do you build with?", a: "We default to Next.js or Astro for marketing sites, and Next.js or Remix for web apps. We use Tailwind for styling, and pick the right CMS per project — usually Sanity, Payload, or Shopify for commerce." },
      { q: "Do you handle SEO?", a: "Yes. Technical SEO (structured data, sitemaps, performance) is standard. Content SEO and ongoing growth is a separate engagement we can scope." },
      { q: "Can I edit the site myself after launch?", a: "Absolutely. We hand off with a CMS your team can use, plus recorded walkthroughs. Most clients are editing within an hour of training." },
      { q: "How fast will the site load?", a: "We target 95+ Lighthouse and sub-1s LCP. We'll show you the audit before launch and again 30 days after." },
      { q: "Will the site work on slow networks?", a: "Yes. We test on throttled 3G and budget Android devices — common in Bangladesh and most emerging markets. We optimise images, fonts, and JS bundles by default." },
      { q: "Do you do redesigns of existing sites?", a: "Often, yes. We start with a 1-week audit covering brand, conversion, performance, and SEO, then quote the redesign with a clear migration plan." },
      { q: "Can you migrate my content from WordPress / Webflow / Wix?", a: "Yes — we have content migration scripts for the common platforms and a manual review pass to keep URL structure and SEO equity intact." },
      { q: "Do you provide copywriting?", a: "We can. Many projects include a copy partner from our network — or we'll work tightly with your in-house writer to make sure the words match the design." },
    ],
  },
  {
    cat: "App Development",
    items: [
      { q: "Native, hybrid, or cross-platform?", a: "Depends on the project. Native (Swift / Kotlin) for performance-critical or platform-specific apps. React Native or Flutter for most consumer apps where time and budget matter." },
      { q: "Do you publish to the App Store and Play Store?", a: "Yes — including screenshots, copy, and the back-and-forth with reviewers. We've shipped 30+ apps and rarely get a first-pass rejection." },
      { q: "Can you take over an app from another team?", a: "Often, yes. We start with a 1-week code audit. If the codebase is salvageable we'll quote the takeover; if not, we'll be honest about that too." },
      { q: "What about ongoing app maintenance?", a: "We offer monthly care plans — bug triage, OS updates, minor features. Most clients stay on care for 12+ months after launch." },
      { q: "How do you handle offline mode?", a: "Offline-first is the default for any app where users might lose connection. We architect with a local cache, optimistic UI, and background sync." },
      { q: "Do you build for tablets and foldables?", a: "Yes. Adaptive layouts for tablets and foldables are part of the design pass — not an afterthought bolted on later." },
      { q: "Can you integrate payments and bKash / Nagad?", a: "Yes. We've integrated Stripe, PayPal, bKash, Nagad, and SSLCommerz. We handle the compliance and reconciliation logic too." },
    ],
  },
  {
    cat: "AI Automation",
    items: [
      { q: "What can AI realistically do for my business today?", a: "Triage, drafting, classification, retrieval — anything where 'good enough, fast' beats 'perfect, slow'. Customer support, lead qualification, and internal ops are the highest-ROI starting points." },
      { q: "Which AI providers do you work with?", a: "Anthropic, OpenAI, Google, and open-weights via self-hosting. We benchmark on your data before recommending." },
      { q: "Is my data safe?", a: "We support zero-retention API tiers, private deployments, and on-prem inference. We'll match your compliance posture exactly." },
      { q: "How do we know it actually works?", a: "We build eval suites before shipping. Every workflow has measurable success criteria and a rollback plan. We review costs and accuracy quarterly." },
      { q: "What does an AI project actually cost to run?", a: "Most workflows we ship cost between $50–$500/month in inference. We instrument every call so you can see usage and tune cost vs. quality knobs." },
      { q: "Can the AI use my existing tools?", a: "Yes — function calling and tool use let the AI read and write to your CRM, helpdesk, calendar, and database. We design the permissions carefully." },
      { q: "What if the model gets it wrong?", a: "We design every workflow with a graceful failure mode and a human-in-the-loop fallback for anything customer-facing or financial." },
    ],
  },
  {
    cat: "Pricing",
    items: [
      { q: "How do you price projects?", a: "Fixed price per phase. We scope the project together, agree on deliverables, and quote a number. No hourly billing, no surprise invoices." },
      { q: "Do you offer payment plans?", a: "Yes — usually 30% upfront, then milestone payments. We're flexible on structure for the right project." },
      { q: "What's your minimum project size?", a: "Around USD 5k for a focused engagement. Below that, we'd recommend a freelance contractor." },
      { q: "Do you do equity / revenue-share deals?", a: "Rarely, and only with founders we've built trust with. We'd rather build a great relationship and then talk about it." },
      { q: "Do you charge in BDT or USD?", a: "Either. Local clients usually invoice in BDT; international clients in USD. We can also accept EUR, GBP, AED, or SGD." },
      { q: "What happens if scope changes mid-project?", a: "We'll quote a change order. Small adjustments are absorbed; meaningful additions get a one-page scope and a price before any work starts." },
      { q: "Are there any hidden costs?", a: "No. Hosting, licences, and 3rd-party services that we recommend are itemised in the proposal. You'll see every recurring cost up front." },
    ],
  },
  {
    cat: "Timeline",
    items: [
      { q: "How long until we see something?", a: "Usually 5-7 days from kickoff: a clickable prototype of the most important screens. Real progress, not a mood board." },
      { q: "What's a typical timeline?", a: "Marketing site: 3-6 weeks. Web app or mobile app: 8-16 weeks. AI workflow: 2-8 weeks. We'll give you a phase-by-phase calendar before signing." },
      { q: "Can you do rush projects?", a: "Sometimes, with a rush surcharge — usually 20-30%. We'll be straight with you about whether the timeline is realistic." },
      { q: "What happens if the project runs late?", a: "If it's our fault, we eat the cost. We've never not delivered, but we put it in writing anyway." },
      { q: "How fast can you start?", a: "Usually within 1–2 weeks of signing. For urgent work we can sometimes start within 48 hours — depending on team availability." },
      { q: "Do you work in our timezone?", a: "We're based in Bogra (GMT+6) but the team works flexibly. We've shipped projects with teams from PT to AEST without anyone losing sleep." },
    ],
  },
  {
    cat: "Support",
    items: [
      { q: "Is there support after launch?", a: "Yes — every project includes a 30-day post-launch support window for bugs and small adjustments." },
      { q: "Do you offer ongoing care plans?", a: "Yes — monthly retainers covering maintenance, minor features, monitoring, and a quarterly strategy review. Most clients stay on care 12+ months." },
      { q: "How do I report a bug?", a: "Linear, Slack, or email — whatever you prefer. We respond within one business day, faster for production issues." },
      { q: "Do you provide hosting?", a: "We can — Vercel, Cloudflare, or AWS. We can also hand off hosting to your DevOps team after launch. Your call." },
      { q: "What about emergency / weekend issues?", a: "Care-plan clients get an on-call rotation with same-day response for production-down issues, weekends included." },
      { q: "Can you train our team?", a: "Yes. Recorded walkthroughs come with every project. Live training sessions and written runbooks are available as add-ons." },
    ],
  },
];

function FAQPage() {
  const [activeCat, setActiveCat] = useState(0);
  const [open, setOpen] = useState(0);
  const [search, setSearch] = useState("");

  const filtered = useMemo(() => {
    if (!search.trim()) return FAQ_DATA;
    const q = search.toLowerCase();
    return FAQ_DATA.map((c) => ({
      ...c,
      items: c.items.filter((it) => it.q.toLowerCase().includes(q) || it.a.toLowerCase().includes(q)),
    })).filter((c) => c.items.length);
  }, [search]);

  const showCat = search.trim() ? null : FAQ_DATA[activeCat];

  return (
    <div className="page-enter">
      <PageHero
        eyebrow="FAQ · The questions everyone asks"
        title={<>Things worth <span style={{ color: "var(--brand)" }}>knowing</span> upfront.</>}
        subtitle="Six categories, ~24 answers. If yours isn't here, drop us a line — we'll answer it personally and probably add it to this page."
      >
        <div style={{ position: "relative", maxWidth: 480 }}>
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search the FAQ..."
            style={{
              width: "100%",
              background: "rgba(255,255,255,0.04)",
              border: "1px solid var(--border-strong)",
              borderRadius: 999,
              padding: "14px 20px 14px 48px",
              color: "var(--fg)",
              fontSize: 15,
              outline: "none",
              fontFamily: "inherit",
            }}
          />
          <svg style={{ position: "absolute", left: 18, top: "50%", transform: "translateY(-50%)" }} width="16" height="16" viewBox="0 0 16 16" fill="none">
            <circle cx="7" cy="7" r="5" stroke="var(--muted)" strokeWidth="1.5"/>
            <path d="M11 11L14 14" stroke="var(--muted)" strokeWidth="1.5" strokeLinecap="round"/>
          </svg>
        </div>
      </PageHero>

      <section style={{ paddingTop: 40 }}>
        <div className="container">
          {search.trim() ? (
            <div>
              {filtered.length === 0 ? (
                <p className="lead">No results for "{search}". Try a different keyword, or <Link to="/contact" style={{ color: "var(--brand)" }}>send us your question</Link>.</p>
              ) : filtered.map((cat) => (
                <div key={cat.cat} style={{ marginBottom: 48 }}>
                  <h3 className="font-display" style={{ fontSize: 24, marginBottom: 16, color: "var(--brand)" }}>{cat.cat}</h3>
                  {cat.items.map((it, i) => (
                    <FAQRow key={it.q} q={it.q} a={it.a} open={open === `${cat.cat}-${i}`} onClick={() => setOpen(open === `${cat.cat}-${i}` ? -1 : `${cat.cat}-${i}`)} />
                  ))}
                </div>
              ))}
            </div>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: 64 }} className="faq-layout">
              <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 }}>Categories</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                  {FAQ_DATA.map((c, i) => (
                    <button
                      key={c.cat}
                      onClick={() => { setActiveCat(i); setOpen(0); }}
                      style={{
                        background: activeCat === i ? "var(--brand-faint)" : "transparent",
                        border: "none",
                        color: activeCat === i ? "var(--brand)" : "var(--fg-2)",
                        padding: "10px 14px",
                        borderRadius: 10,
                        textAlign: "left",
                        fontSize: 14, fontWeight: 500,
                        cursor: "pointer",
                        transition: "all 0.2s var(--ease)",
                        fontFamily: "inherit",
                      }}
                    >
                      {c.cat}
                    </button>
                  ))}
                </div>
              </aside>
              <div>
                <h2 className="font-display" style={{ fontSize: 36, marginBottom: 32, letterSpacing: "-0.025em" }}>{showCat.cat}</h2>
                {showCat.items.map((it, i) => (
                  <FAQRow key={it.q} q={it.q} a={it.a} open={open === i} onClick={() => setOpen(open === i ? -1 : i)} />
                ))}
              </div>
            </div>
          )}
        </div>
        <style>{`
          @media (max-width: 880px) {
            .faq-layout { grid-template-columns: 1fr !important; gap: 32px !important; }
            .faq-layout > aside { position: static !important; }
            .faq-layout > aside > div:last-child { flex-direction: row !important; flex-wrap: wrap; }
          }
        `}</style>
      </section>
    </div>
  );
}

function FAQRow({ q, a, open, onClick }) {
  return (
    <div onClick={onClick} style={{ borderTop: "1px solid var(--border)", padding: "24px 0", cursor: "pointer" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 24 }}>
        <h3 className="font-display" style={{ fontSize: 19, fontWeight: 600, letterSpacing: "-0.01em" }}>{q}</h3>
        <div style={{
          width: 32, height: 32, borderRadius: "50%", border: "1px solid var(--border-strong)",
          display: "grid", placeItems: "center", flexShrink: 0,
          color: open ? "var(--brand)" : "var(--fg-2)",
          transform: open ? "rotate(45deg)" : "none",
          transition: "all 0.3s var(--ease)",
        }}>+</div>
      </div>
      <div style={{
        overflow: "hidden",
        maxHeight: open ? 240 : 0,
        transition: "max-height 0.4s var(--ease), margin-top 0.4s var(--ease), opacity 0.4s var(--ease)",
        marginTop: open ? 16 : 0,
        opacity: open ? 1 : 0,
      }}>
        <p style={{ color: "var(--fg-2)", margin: 0, maxWidth: 720 }}>{a}</p>
      </div>
    </div>
  );
}

window.FAQPage = FAQPage;
