// FAQ accordion. One open at a time, smooth max-height expand.

// === IBKR step-strip mockups ===========================================
// Stylised HTML/CSS "window" used as a placeholder until a real screenshot
// is dropped into upload_perso/. Each step card accepts an optional `image`
// path; when provided it replaces the mockup but keeps the same aspect
// ratio so the strip layout never shifts.

function MockWindow({ title, children }) {
  return (
    <div className="h-full w-full flex flex-col card1 overflow-hidden">
      <div className="flex items-center gap-1.5 px-2.5 h-6 border-b border-border1 bg-bg2 shrink-0">
        <span className="h-2 w-2 rounded-full bg-[#ff5f57]" />
        <span className="h-2 w-2 rounded-full bg-[#febc2e]" />
        <span className="h-2 w-2 rounded-full bg-[#28c840]" />
        <span className="ml-2 text-[9.5px] text-subtlefg truncate">{title}</span>
      </div>
      <div className="flex-1 min-h-0 p-2.5 text-[10px] text-mutedfg flex flex-col gap-1.5">
        {children}
      </div>
    </div>
  );
}

function IbkrFlexQueryMockup() {
  return (
    <MockWindow title="IBKR · Account Management">
      <div className="text-[9px] uppercase tracking-wider text-subtlefg">Flex Queries</div>
      <div className="rounded-md border border-border1 bg-card2 px-2 py-1.5 flex items-center justify-between">
        <span className="text-fg text-[10px] font-medium">Activity Flex Query</span>
        <span className="h-1.5 w-1.5 rounded-full bg-positive" />
      </div>
      <div className="rounded-md border border-border1 bg-card2 px-2 py-1.5">
        <span className="text-[9.5px] text-mutedfg">Sections: Trades, Cash, Dividends…</span>
      </div>
      <div className="mt-auto flex justify-end">
        <span className="btn-primary inline-flex items-center text-[9.5px] font-medium px-2 py-1 rounded-md">
          Create
        </span>
      </div>
    </MockWindow>
  );
}

function IbkrConnectMockup() {
  return (
    <MockWindow title="DashFolio · Connect">
      <div className="space-y-1">
        <div className="text-[9px] uppercase tracking-wider text-subtlefg">Flex token</div>
        <div className="rounded-md border border-border1 bg-card2 px-2 py-1.5 flex items-center gap-1.5">
          <IcoLock size={10} className="text-positive shrink-0" />
          <span className="font-mono text-[9.5px] text-fg truncate">••••••••••••••••3f9a</span>
        </div>
      </div>
      <div className="space-y-1">
        <div className="text-[9px] uppercase tracking-wider text-subtlefg">Query ID</div>
        <div className="rounded-md border border-border1 bg-card2 px-2 py-1.5">
          <span className="font-mono text-[9.5px] text-fg">428193</span>
        </div>
      </div>
      <div className="mt-auto flex justify-end">
        <span className="btn-primary inline-flex items-center text-[9.5px] font-medium px-2 py-1 rounded-md">
          Save & connect
        </span>
      </div>
    </MockWindow>
  );
}

function IbkrImportsMockup() {
  const rows = [
    { d: "May 22", n: "1,284 rows" },
    { d: "May 21", n: "1,217 rows" },
    { d: "May 20", n: "1,196 rows" },
  ];
  return (
    <MockWindow title="DashFolio · Imports">
      <div className="flex items-center justify-between">
        <span className="text-[9.5px] text-fg">Scheduled daily · 06:30</span>
        <span className="rounded-full bg-positive/15 text-positive px-1.5 py-px text-[8.5px] font-medium">active</span>
      </div>
      <div className="rounded-md border border-border1 bg-card2 divide-y divide-border2">
        {rows.map((r, i) => (
          <div key={i} className="px-2 py-1 flex items-center justify-between gap-2">
            <span className="flex items-center gap-1.5 text-[9.5px] text-fg">
              <span className="h-3 w-3 rounded-full bg-positive/20 inline-flex items-center justify-center text-positive">
                <IcoCheck size={8} />
              </span>
              {r.d}
            </span>
            <span className="font-mono text-[9px] text-mutedfg">{r.n}</span>
          </div>
        ))}
      </div>
      <div className="mt-auto flex justify-end">
        <span className="btn-secondary inline-flex items-center text-[9.5px] font-medium px-2 py-1 rounded-md">
          Run now
        </span>
      </div>
    </MockWindow>
  );
}

function StepCard({ n, caption, mockup, image, alt }) {
  return (
    <div className="card2 rounded-xl overflow-hidden flex flex-col">
      <div className="relative aspect-[16/10] bg-bg2 border-b border-border1">
        {image ? (
          <img
            src={image}
            alt={alt || caption}
            className="absolute inset-0 h-full w-full object-cover"
          />
        ) : (
          <div className="absolute inset-0 p-2.5">{mockup}</div>
        )}
      </div>
      <div className="flex items-start gap-2.5 px-3 py-2.5">
        <span className="shrink-0 h-5 w-5 rounded-full bg-primary/15 border border-primary/40 text-primary text-[10.5px] font-semibold inline-flex items-center justify-center">
          {n}
        </span>
        <span className="text-[12.5px] leading-snug text-fg">{caption}</span>
      </div>
    </div>
  );
}

// `images` lets a caller swap any of the three illustrations for a real
// screenshot path (e.g. ["upload_perso/faq-ibkr-step1.png", null, null]).
// Missing/empty entries fall back to the HTML/CSS mockup.
function IbkrStepsStrip({ images }) {
  const imgs = Array.isArray(images) ? images : [];
  const steps = [
    { caption: "Create the Flex Query in Account Management", mockup: <IbkrFlexQueryMockup /> },
    { caption: "Paste the token and Query ID",                mockup: <IbkrConnectMockup /> },
    { caption: "Reports import on your schedule",             mockup: <IbkrImportsMockup /> },
  ];
  return (
    <div className="mt-4 grid grid-cols-1 md:grid-cols-3 gap-3">
      {steps.map((s, i) => (
        <StepCard
          key={i}
          n={i + 1}
          caption={s.caption}
          mockup={s.mockup}
          image={imgs[i] || null}
        />
      ))}
    </div>
  );
}

// === RealTest → OrderClerk → IBKR flow diagram ==========================
// SVG-based for pixel-perfect arrow alignment; foreignObject hosts the
// HTML node cards so they keep Tailwind theming and crisp text rendering.

function RtfdNode({ accent, Icon, title, sub }) {
  const ACC = {
    violet:  { bg: "bg-violet-500/10",  ring: "border-violet-500/30",  ic: "text-violet-500",  icBg: "bg-violet-500/15" },
    emerald: { bg: "bg-emerald-500/10", ring: "border-emerald-500/30", ic: "text-emerald-500", icBg: "bg-emerald-500/15" },
    amber:   { bg: "bg-amber-500/10",   ring: "border-amber-500/30",   ic: "text-amber-500",   icBg: "bg-amber-500/15" },
    slate:   { bg: "bg-card2",          ring: "border-border1",        ic: "text-mutedfg",     icBg: "bg-bg1" },
    primary: { bg: "bg-primary/10",     ring: "border-primary/40",     ic: "text-primary",     icBg: "bg-primary/15" },
  };
  const c = ACC[accent] || ACC.slate;
  return (
    <div className={`h-full w-full rounded-xl border ${c.ring} ${c.bg} px-3 flex items-center gap-2.5`}>
      <span className={`shrink-0 h-9 w-9 rounded-lg ${c.icBg} ${c.ic} inline-flex items-center justify-center`}>
        <Icon size={16} />
      </span>
      <div className="min-w-0 flex-1">
        <div className="text-[12.5px] font-semibold text-fg leading-tight truncate">{title}</div>
        <div className="text-[10.5px] text-mutedfg leading-snug mt-0.5">{sub}</div>
      </div>
    </div>
  );
}

function RealtestFlowDiagram() {
  return (
    <div className="mt-5 rounded-2xl border border-border1 bg-bg2/30 p-4 md:p-6">
      <div className="text-[10px] font-semibold uppercase tracking-wider text-subtlefg text-center mb-4">
        How the round-trip connects
      </div>
      <div className="overflow-x-auto -mx-1 px-1">
        <svg
          viewBox="0 0 660 400"
          xmlns="http://www.w3.org/2000/svg"
          className="block w-full min-w-[520px] max-w-3xl mx-auto h-auto text-border1"
          aria-label="RealTest produces order files routed through OrderClerk to IBKR; the DashFolioSync Agent syncs trade history to DashFolio, which also pulls Flex reports from IBKR"
        >
          <defs>
            <marker id="rtfd-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse">
              <path d="M0,0 L10,5 L0,10 z" fill="currentColor" />
            </marker>
          </defs>

          {/* Trader's PC dashed container */}
          <rect x="12" y="22" width="306" height="368" rx="14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeDasharray="5 4" />
          <text x="30" y="44" fontSize="10" letterSpacing="0.8" className="fill-subtlefg" style={{ fontWeight: 500 }}>
            TRADER&apos;S PC (WINDOWS)
          </text>

          {/* Nodes — left column (inside PC) */}
          <foreignObject x="32" y="64" width="266" height="60">
            <RtfdNode accent="violet"  Icon={IcoSparkle}   title="RealTest"             sub="Backtest + signals" />
          </foreignObject>
          <foreignObject x="32" y="176" width="266" height="60">
            <RtfdNode accent="emerald" Icon={IcoShuffle}   title="OrderClerk"           sub="Routes to broker" />
          </foreignObject>
          <foreignObject x="32" y="304" width="266" height="60">
            <RtfdNode accent="amber"   Icon={IcoUpload}    title="DashFolioSync Agent" sub="Bridges PC to server" />
          </foreignObject>

          {/* Nodes — right column (external) */}
          <foreignObject x="388" y="176" width="258" height="60">
            <RtfdNode accent="slate"   Icon={IcoBriefcase} title="IBKR"                 sub="Executes orders" />
          </foreignObject>
          <foreignObject x="388" y="304" width="258" height="60">
            <RtfdNode accent="primary" Icon={IcoTarget}    title="DashFolio"    sub="Matches to strategy" />
          </foreignObject>

          {/* Vertical arrows (left column) */}
          <line x1="165" y1="128" x2="165" y2="172" stroke="currentColor" strokeWidth="1.2" markerEnd="url(#rtfd-arrow)" />
          <text x="173" y="155" fontSize="10" className="fill-subtlefg">order files</text>

          <line x1="165" y1="240" x2="165" y2="300" stroke="currentColor" strokeWidth="1.2" markerEnd="url(#rtfd-arrow)" />
          <text x="173" y="275" fontSize="10" className="fill-subtlefg">trade history</text>

          {/* Vertical arrow (right column) */}
          <line x1="517" y1="240" x2="517" y2="300" stroke="currentColor" strokeWidth="1.2" markerEnd="url(#rtfd-arrow)" />
          <text x="525" y="275" fontSize="10" className="fill-subtlefg">Flex Query</text>

          {/* Horizontal bidirectional arrows */}
          <line x1="302" y1="206" x2="386" y2="206" stroke="currentColor" strokeWidth="1.2" markerStart="url(#rtfd-arrow)" markerEnd="url(#rtfd-arrow)" />
          <text x="344" y="198" fontSize="10" className="fill-subtlefg" textAnchor="middle">execution + fills</text>

          <line x1="302" y1="334" x2="386" y2="334" stroke="currentColor" strokeWidth="1.2" markerStart="url(#rtfd-arrow)" markerEnd="url(#rtfd-arrow)" />
          <text x="344" y="326" fontSize="10" className="fill-subtlefg" textAnchor="middle">uploads + syncs</text>
        </svg>
      </div>
    </div>
  );
}

// === FAQ accordion =====================================================

function FaqItem({ q, a, extra, isOpen, onToggle }) {
  const ref = React.useRef(null);
  const [h, setH] = React.useState(0);
  React.useEffect(() => {
    if (ref.current) setH(ref.current.scrollHeight);
  }, [isOpen, a, extra]);
  return (
    <div className="border-b border-border1">
      <button
        type="button"
        onClick={onToggle}
        className="w-full flex items-center justify-between gap-4 py-5 text-left group"
      >
        <span className="text-[15px] font-medium text-fg group-hover:text-primary transition-colors">{q}</span>
        <span className={`shrink-0 h-6 w-6 rounded-full border border-border1 flex items-center justify-center text-mutedfg transition-transform ${isOpen ? "rotate-45 bg-primary/15 border-primary/40 text-primary" : ""}`}>
          <IcoPlus size={12} />
        </span>
      </button>
      <div
        style={{ maxHeight: isOpen ? h : 0 }}
        className="overflow-hidden transition-[max-height] duration-300 ease-out"
      >
        <div ref={ref} className="pb-5 pr-10 text-[14px] text-mutedfg leading-relaxed">
          {a}
          {extra}
        </div>
      </div>
    </div>
  );
}

const IBKR_FAQ_Q = "How does DashFolio connect to Interactive Brokers?";
const REALTEST_FAQ_Q = "Does it work with RealTest Backtesting Software?";
const CSV_FAQ_Q = "Can I import historical trades from CSV?";

function ImageLightbox({ src, alt, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);
  return (
    <div
      role="dialog"
      aria-modal="true"
      onClick={onClose}
      className="fixed inset-0 z-[100] bg-black/80 backdrop-blur-sm flex items-center justify-center p-6 cursor-zoom-out"
    >
      <button
        type="button"
        onClick={onClose}
        aria-label="Close"
        className="absolute top-4 right-4 h-9 w-9 rounded-full bg-bg2/80 hover:bg-bg2 text-fg border border-border1 inline-flex items-center justify-center"
      >
        <IcoPlus size={14} className="rotate-45" />
      </button>
      <img
        src={src}
        alt={alt}
        onClick={(e) => e.stopPropagation()}
        className="max-h-[90vh] max-w-[92vw] w-auto h-auto rounded-xl border border-border1 shadow-2xl cursor-default"
      />
    </div>
  );
}

function CsvUploadShot() {
  const [open, setOpen] = React.useState(false);
  const src = "/landing-assets/faq-upload-trade-file.png";
  const alt = "Upload Trade File dialog for picking a CSV or XML exported from your broker";
  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        aria-label="View larger screenshot"
        className="mt-4 mx-auto block card2 rounded-xl overflow-hidden border border-border1 max-w-[260px] cursor-zoom-in hover:border-primary/40 transition-colors"
      >
        <img src={src} alt={alt} className="block w-full h-auto" />
      </button>
      {open && <ImageLightbox src={src} alt={alt} onClose={() => setOpen(false)} />}
    </>
  );
}

function faqExtraFor(q) {
  if (q === IBKR_FAQ_Q) return <IbkrStepsStrip />;
  if (q === REALTEST_FAQ_Q) return <RealtestFlowDiagram />;
  if (q === CSV_FAQ_Q) return <CsvUploadShot />;
  return null;
}

function FAQ() {
  const [openIdx, setOpenIdx] = React.useState(-1);
  return (
    <Section id="faq"
      className="pb-16 md:pb-24"
      eyebrow="Questions"
      title="Frequently asked questions."
      sub={<>
        Can't find what you're looking for? Email us and we'll get back to you as soon as we can.{" "}
        <a href="/contact" className="inline-flex items-center gap-1 text-primary hover:underline whitespace-nowrap">
          Contact support <IcoArrowRight size={12} />
        </a>
      </>}
    >
      <div>
        <div className="card1 px-6">
          {FAQS.map(([q, a], i) => (
            <FaqItem
              key={i}
              q={q}
              a={a}
              extra={faqExtraFor(q)}
              isOpen={openIdx === i}
              onToggle={() => setOpenIdx(openIdx === i ? -1 : i)}
            />
          ))}
        </div>
        <div className="mt-6 flex justify-center">
          <a href="/faq" className="inline-flex items-center gap-1.5 text-sm text-primary hover:underline">
            See all FAQs <IcoArrowRight size={13} />
          </a>
        </div>
      </div>
    </Section>
  );
}

Object.assign(window, { FAQ, IbkrStepsStrip, RealtestFlowDiagram });
