/* Deep Dive — Q11 (A + B + C + D + G)
   Tab 1: Thesis Fit (per-criterion + anti-thesis)
   Tab 2: Fundamentals (charts)
   Tab 3: Recent Narrative
   Sidebar: Notes
   Layout variant via tweak: 'tabs' or 'scroll'. */

const { useState: useStateDD } = React;

function DeepDiveScreen({ profileId, thesisId, ticker, onBack, layout = "tabs" }) {
  const c =
    dbq.candidateByTicker(profileId, ticker) ||
    dbq.candidatesForThesis(thesisId)[0] ||
    dbq.candidatesForProfile(profileId)[0];
  const thesis = dbq.thesisById(c.thesis_id);
  const totalInThesis = dbq.candidatesForThesis(c.thesis_id).length;
  const [tab, setTab] = useStateDD("fit");
  const [notes, setNotes] = useStateDD("Watch Q3 earnings — capex commentary from top customer.\n\nIf custom-ASIC mix slips, fit score drops.");

  const Section = ({ id, title, children }) =>
    layout === "scroll" ? (
      <section id={id} style={{ marginTop: 32, scrollMarginTop: 80 }}>
        <div className="label" style={{ marginBottom: 8 }}>{title}</div>
        {children}
      </section>
    ) : (
      tab === id && <div className="fade-in">{children}</div>
    );

  return (
    <div style={{ background: "var(--bg)", minHeight: "100vh" }}>
      <Disclaimer />

      {/* Header */}
      <div style={{ borderBottom: "1px solid var(--line)", padding: "20px 24px", maxWidth: 1280, margin: "0 auto" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>
          <div>
            <div className="crumbs" style={{ marginBottom: 8 }}>
              <span>thesis</span><span className="crumb-sep">/</span>
              <span>{thesis.title.toLowerCase()}</span><span className="crumb-sep">/</span>
              <span className="crumb-active">{c.ticker}</span>
            </div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
              <h1 style={{ margin: 0, fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 38, letterSpacing: "-0.02em" }}>
                {c.name}
              </h1>
              <span className="mono" style={{ fontSize: 18, color: "var(--ink-3)" }}>{c.ticker}</span>
            </div>
            <div style={{ display: "flex", gap: 16, marginTop: 8, fontSize: 12, color: "var(--ink-3)", flexWrap: "wrap", alignItems: "center" }}>
              <span>{c.sector}</span>
              <span>·</span>
              <span className="mono">{c.mcap} mcap</span>
              {c.sources && c.sources.length > 0 && (
                <>
                  <span>·</span>
                  <span className="mono">{c.sources.length} cited source{c.sources.length === 1 ? "" : "s"}</span>
                  <span style={{ display: "inline-flex", gap: 4, flexWrap: "wrap" }}>
                    {c.sources.map((src, si) => (
                      <Cite key={si} label={src.label} num={src.detail} href={src.source} />
                    ))}
                  </span>
                </>
              )}
            </div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <div style={{ textAlign: "right" }}>
              <FitScore value={c.fit} big />
              <div style={{ width: 140, marginTop: 6 }}>
                <ScoreBar value={c.fit} height={3} />
              </div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)", marginTop: 4 }}>
                rank #{c.rank} of {totalInThesis}
              </div>
            </div>
            <button className="btn btn-primary"><Icon name="bell" size={13} /> Activate tracking</button>
            <button className="btn btn-ghost btn-sm" onClick={onBack}><Icon name="close" size={14} /></button>
          </div>
        </div>
      </div>

      {/* Body */}
      <div style={{ maxWidth: 1280, margin: "0 auto", padding: "20px 24px 80px", display: "grid", gridTemplateColumns: "1fr 320px", gap: 28 }} className="dd-grid">
        <div>
          {layout === "tabs" && (
            <Tabs
              tabs={[
                { id: "fit", label: "Thesis Fit" },
                { id: "fund", label: "Fundamentals" },
                { id: "news", label: "Recent Narrative", count: 12 },
              ]}
              active={tab}
              onChange={setTab}
            />
          )}

          <Section id="fit" title="Thesis fit">
            <PerCriterion c={c} />
            <AntiThesisCheck c={c} />
          </Section>

          <Section id="fund" title="Fundamentals">
            <FundamentalsTab c={c} />
          </Section>

          <Section id="news" title="Recent narrative">
            <NewsTab profileId={c.profile_id} />
          </Section>
        </div>

        <NotesSidebar c={c} notes={notes} setNotes={setNotes} />
      </div>
    </div>
  );
}

function PerCriterion({ c }) {
  const criteria = dbq.criteriaForProfile(c.profile_id);
  const scoresByCriterionId = Object.fromEntries(
    dbq.scoresForCandidate(c.id).map((s) => [s.criterion_id, s])
  );
  return (
    <div style={{ marginTop: 24 }}>
      <div className="label" style={{ marginBottom: 12 }}>Per-criterion scorecard</div>
      <div style={{ display: "grid", gap: 12 }}>
        {criteria.map((cr) => {
          const s = scoresByCriterionId[cr.id];
          if (!s) return null;
          return (
            <div key={cr.id} className="card" style={{ padding: 14 }}>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 90px 60px", gap: 12, alignItems: "center" }}>
                <div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontSize: 14, fontWeight: 500 }}>{cr.name}</span>
                    <span className="tag" style={{ fontSize: 9 }}>
                      {cr.eval_method === "fundamentals" ? "FMP" : "qual"}
                    </span>
                  </div>
                  <div style={{ marginTop: 6 }}>
                    <ScoreBar value={s.score} />
                  </div>
                </div>
                <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>
                  weight {Math.round(cr.weight * 100)}%
                </div>
                <div className="mono" style={{ fontSize: 18, fontWeight: 600, textAlign: "right" }}>
                  {s.score.toFixed(2)}
                </div>
              </div>
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: "1px dashed var(--line)", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.55 }}>
                {s.rationale}
                <span style={{ marginLeft: 4 }}>
                  {s.citations.filter((cit) => cit.source).map((cit, ci) => (
                    <Cite key={ci} label={cit.label} num={cit.detail} href={cit.source} />
                  ))}
                </span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function AntiThesisCheck({ c }) {
  const bullets = dbq.antiThesesForThesis(c.thesis_id);
  const triggers = dbq.antiTriggersForCandidate(c.id);
  const triggeredById = Object.fromEntries(triggers.map((t) => [t.anti_thesis_id, t]));
  return (
    <div style={{ marginTop: 24 }}>
      <div className="label" style={{ marginBottom: 12 }}>Anti-thesis check</div>
      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        {bullets.map((b, i) => {
          const trigger = triggeredById[b.id];
          const triggered = !!trigger;
          return (
            <div key={b.id} style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 16px", borderBottom: i < bullets.length - 1 ? "1px solid var(--line)" : "none", background: triggered ? "color-mix(in oklch, var(--neg) 8%, transparent)" : undefined }}>
              <div style={{ marginTop: 2 }}>
                {triggered ? (
                  <Icon name="warn" size={14} style={{ color: "var(--neg)" }} />
                ) : (
                  <Icon name="check2" size={14} style={{ color: "var(--pos)" }} />
                )}
              </div>
              <div style={{ flex: 1, fontSize: 13, color: triggered ? "var(--ink)" : "var(--ink-2)" }}>
                {b.text}
                {b.source && (
                  <a
                    href={b.source}
                    target="_blank"
                    rel="noopener noreferrer"
                    title={b.source}
                    style={{ marginLeft: 6, fontSize: 11, color: "var(--ink-3)", textDecoration: "underline" }}
                  >
                    source
                  </a>
                )}
                {triggered && trigger.note && (
                  <div className="mono" style={{ fontSize: 11, marginTop: 4, color: "var(--neg)" }}>
                    triggered — {trigger.note}
                  </div>
                )}
              </div>
              <div className="mono" style={{ fontSize: 11, color: triggered ? "var(--neg)" : "var(--pos)", textTransform: "uppercase", letterSpacing: "0.06em" }}>
                {triggered ? "fail" : "clear"}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function FundamentalsTab({ c }) {
  const charts = [
    { label: "Revenue (TTM)", value: "$51.6B", delta: "+33%", data: c.spark },
    { label: "FCF margin", value: "49%", delta: "+6pp", data: spark(c.rank * 3) },
    { label: "Operating margin", value: "44%", delta: "+4pp", data: spark(c.rank * 5) },
    { label: "Net debt / EBITDA", value: "1.2×", delta: "−0.3", data: spark(c.rank * 7).map((v) => 1 - v) },
    { label: "EV / EBITDA", value: "22.4×", delta: "in line", data: spark(c.rank * 11) },
    { label: "FCF / share", value: "$24.10", delta: "+18%", data: spark(c.rank * 13) },
  ];
  return (
    <div style={{ marginTop: 24, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(240px, 1fr))", gap: 14 }}>
      {charts.map((ch, i) => (
        <div key={i} className="card">
          <div className="label" style={{ fontSize: 10 }}>{ch.label}</div>
          <div style={{ display: "flex", alignItems: "baseline", gap: 8, margin: "6px 0 10px" }}>
            <span className="mono" style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.02em" }}>{ch.value}</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--pos)" }}>{ch.delta}</span>
          </div>
          <Sparkline data={ch.data} height={42} fill />
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6 }}>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-4)" }}>FY21</span>
            <span className="mono" style={{ fontSize: 9, color: "var(--ink-4)" }}>FY24</span>
          </div>
        </div>
      ))}
    </div>
  );
}

function NewsTab({ profileId }) {
  const news = dbq.newsForProfile(profileId);
  // Repeat to fill the 6-card display while news authoring is light.
  const display = news.concat(news).slice(0, 6);
  return (
    <div style={{ marginTop: 24, display: "grid", gap: 10 }}>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>
        Last 30 days · filtered for thesis relevance
      </div>
      {display.map((n, i) => (
        <div key={n.id + "-" + i} className="card card-hover" style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
          <div style={{ width: 90, paddingTop: 2 }}>
            <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)", textTransform: "uppercase", letterSpacing: "0.08em" }}>{n.type}</div>
            <div className="mono" style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>{n.when}</div>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, color: "var(--ink)", lineHeight: 1.45 }}>{n.title}</div>
            <div style={{ marginTop: 6, display: "flex", gap: 8, alignItems: "center" }}>
              <span className="mono" style={{ fontSize: 11, color: "var(--ink-4)" }}>{n.source}</span>
              <span className={"tag " + (n.impact === "supports" ? "tag-pos" : n.impact === "challenges" ? "tag-neg" : "")}>
                <span className="tag-dot" />
                {n.impact}
              </span>
            </div>
          </div>
          <Icon name="external" size={14} style={{ color: "var(--ink-4)" }} />
        </div>
      ))}
    </div>
  );
}

function NotesSidebar({ c, notes, setNotes }) {
  return (
    <aside className="dd-sidebar">
      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: "12px 14px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <span className="label">Your notes</span>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>private</span>
        </div>
        <textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          style={{
            width: "100%",
            minHeight: 160,
            padding: 14,
            border: "none",
            background: "transparent",
            outline: "none",
            resize: "vertical",
            fontFamily: "inherit",
            fontSize: 13,
            lineHeight: 1.6,
            color: "var(--ink)",
          }}
        />
        <div style={{ padding: "10px 14px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "space-between" }}>
          <span className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>autosaved · just now</span>
        </div>
      </div>

      <div className="card" style={{ marginTop: 14 }}>
        <div className="label" style={{ marginBottom: 10 }}>Snapshot history</div>
        <div style={{ display: "grid", gap: 6 }}>
          {[
            ["2026-04-26", "0.91", "+0.04", true],
            ["2026-04-19", "0.87", "+0.02", false],
            ["2026-04-12", "0.85", "—", false],
            ["2026-04-05", "0.85", "−0.01", false],
          ].map(([d, s, dt, current], i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 50px 50px", gap: 8, padding: "6px 0", borderBottom: i < 3 ? "1px dashed var(--line)" : "none", alignItems: "center" }}>
              <span className="mono" style={{ fontSize: 11, color: current ? "var(--ink)" : "var(--ink-3)" }}>{d}{current && " ←"}</span>
              <span className="mono" style={{ fontSize: 12, fontWeight: current ? 600 : 400 }}>{s}</span>
              <span className="mono" style={{ fontSize: 10, color: dt.startsWith("+") ? "var(--pos)" : dt.startsWith("−") ? "var(--neg)" : "var(--ink-4)" }}>{dt}</span>
            </div>
          ))}
        </div>
        <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)", marginTop: 10 }}>
          schema-only in v1 · diffs ship in v1.5
        </div>
      </div>
    </aside>
  );
}

Object.assign(window, { DeepDiveScreen });
