// detail.jsx — Skill detail page (with team variant)

const { useState: useStateD, useMemo: useMemoD } = React;

function DetailScreen({ skillId, onOpen, onInstall, onNav, teamView, installedSet }) {
  const skill = SKILLS_BY_ID[skillId];
  const [tab, setTab] = useStateD("overview");
  const [exampleTab, setExampleTab] = useStateD(0);
  if (!skill) return <div className="page" style={{ padding: 40 }}>Skill not found.</div>;

  const reviews = REVIEWS[skill.id] || [];
  const related = (RELATED[skill.id] || []).map(id => SKILLS_BY_ID[id]).filter(Boolean);
  const installed = installedSet.has(skill.id);

  const trustItems = [
    { label: "Version", value: skill.version },
    { label: "Last updated", value: skill.last_updated },
    { label: "Installs (30d)", value: skill.installs_label },
    { label: "Activation", value: `${Math.round(skill.activation_rate * 100)}%` },
    { label: "Compatibility", value: skill.compatibility.join(", ") },
    { label: "License", value: skill.license },
    { label: "Pricing", value: skill.pricing },
  ];

  return (
    <div className="col">
      {/* Breadcrumb */}
      <div className="page" style={{ paddingTop: 20 }}>
        <div className="row gap-2 meta">
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("home"); }} style={{ textDecoration: "none", color: "var(--ink-3)" }}>Discover</a>
          <I.ChevR size={10} />
          <a href="#" onClick={(e) => { e.preventDefault(); onNav("browse", { cat: skill.category }); }} style={{ textDecoration: "none", color: "var(--ink-3)" }}>{skill.category}</a>
          <I.ChevR size={10} />
          <span style={{ color: "var(--ink-1)" }}>{skill.name}</span>
        </div>
      </div>

      {/* HEADER */}
      <header className="page" style={{ paddingTop: 28, paddingBottom: 28 }}>
        <div className="row gap-5" style={{ alignItems: "flex-start" }}>
          <SkillAvatar skill={skill} size={72} />
          <div className="grow col gap-3">
            <div className="row gap-3 wrap" style={{ alignItems: "center" }}>
              <h1 className="h2" style={{ margin: 0 }}>{skill.name}</h1>
              {skill.badges?.map(b => <Badge key={b} kind={b} />)}
              {teamView && skill.team_approved && <Badge kind="team" />}
            </div>
            <div className="body" style={{ color: "var(--ink-2)", maxWidth: 720 }}>{skill.one_liner}</div>
            <div className="row gap-3 wrap meta">
              <span className="row gap-1"><I.User size={12} /> {skill.author}</span>
              <span style={{ color: "var(--ink-5)" }}>·</span>
              <span className="row gap-1"><I.Clock size={12} /> Updated {skill.last_updated}</span>
              <span style={{ color: "var(--ink-5)" }}>·</span>
              <span className="row gap-1"><I.Download size={12} /> {skill.installs_label} installs</span>
              <span style={{ color: "var(--ink-5)" }}>·</span>
              <span className="row gap-1"><Stars value={skill.rating} size={11} /> {skill.rating} ({skill.reviews})</span>
            </div>
            <div className="row gap-2 wrap" style={{ marginTop: 4 }}>
              <span className="tag">{skill.category}</span>
              {skill.use_cases?.map(u => <span key={u} className="tag">#{u}</span>)}
              {skill.compatibility.map(c => <span key={c} className="tag">{c}</span>)}
            </div>
          </div>
          <div className="row gap-2" style={{ flex: "0 0 auto" }}>
            <button className="icon-btn" title="Save"><I.Bookmark size={16} /></button>
            <button className="icon-btn" title="Share"><I.Share size={16} /></button>
            <button className={`btn btn-lg ${installed ? "" : "btn-primary"}`}
              onClick={() => installed ? null : onInstall(skill)}>
              {installed ? <><I.Check size={14} /> Installed</> : <>Install <I.Download size={14} /></>}
            </button>
          </div>
        </div>
      </header>

      <div className="hr" />

      {/* BODY */}
      <div className="page" style={{ padding: "32px 28px 64px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 40, alignItems: "start" }}>
          {/* MAIN COLUMN */}
          <main className="col gap-7">
            {/* Tabs */}
            <div className="row" style={{ borderBottom: "1px solid var(--line)", gap: 4, marginTop: -4 }}>
              {[
                ["overview","Overview"],
                ["preview","Preview"],
                ["compatibility","Compatibility"],
                ["trust","Trust & safety"],
                ["reviews",`Reviews · ${skill.reviews}`],
                ["versions","Versions"],
              ].map(([id, label]) => (
                <button key={id} className="unstyled"
                  onClick={() => setTab(id)}
                  style={{
                    padding: "10px 12px",
                    font: "500 13.5px/1 var(--font-sans)",
                    color: tab === id ? "var(--ink)" : "var(--ink-3)",
                    borderBottom: tab === id ? "2px solid var(--ink)" : "2px solid transparent",
                    marginBottom: -1, cursor: "pointer",
                  }}>{label}</button>
              ))}
            </div>

            {tab === "overview" && (
              <div className="col gap-7">
                {/* Overview */}
                <section className="col gap-4">
                  <h3 className="h4" style={{ margin: 0 }}>What it does</h3>
                  <p className="body" style={{ margin: 0, color: "var(--ink-1)", maxWidth: 760 }}>{skill.description}</p>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 4 }}>
                    <FactBlock title="Best for" items={skill.best_for} tone="green" />
                    <FactBlock title="Not for" items={skill.not_for} tone="amber" />
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                    <FactBlock title="Inputs" items={skill.inputs} mono />
                    <FactBlock title="Outputs" items={skill.outputs} mono />
                  </div>
                </section>

                {/* Preview */}
                <section className="col gap-4">
                  <SectionHead title="Try it before you install" subtitle="Sample invocation and output." />
                  <PreviewBlock skill={skill} tab={exampleTab} setTab={setExampleTab} />
                </section>

                {/* How it works */}
                <section className="col gap-4">
                  <SectionHead title="How it works" />
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                    <FactBlock title="Trigger conditions" items={skill.triggers} mono />
                    <FactBlock title="Failure modes" items={skill.limits} />
                  </div>
                  <div className="card col" style={{ padding: 0 }}>
                    {skill.steps.map((s, i) => (
                      <div key={i} className="row gap-3" style={{
                        padding: "12px 16px",
                        borderTop: i ? "1px solid var(--line-soft)" : "none",
                        alignItems: "center",
                      }}>
                        <span style={{
                          width: 22, height: 22, borderRadius: 6,
                          background: "var(--iris-50)", color: "var(--iris-700)",
                          display: "inline-flex", alignItems: "center", justifyContent: "center",
                          font: "600 11px/1 var(--font-mono)", flex: "0 0 auto",
                        }}>{i + 1}</span>
                        <span className="body-sm" style={{ color: "var(--ink-1)" }}>{s}</span>
                      </div>
                    ))}
                  </div>
                </section>
              </div>
            )}

            {tab === "preview" && (
              <PreviewBlock skill={skill} tab={exampleTab} setTab={setExampleTab} large />
            )}

            {tab === "compatibility" && (
              <div className="col gap-4">
                <SectionHead title="Compatibility" />
                <div className="card" style={{ padding: 18 }}>
                  <CompatRow label="Runtimes" value={skill.compatibility.join(", ")} good />
                  <CompatRow label="Required tools" value={skill.deps?.length ? skill.deps.join(", ") : "None"} good={!skill.deps?.length} />
                  <CompatRow label="Models / providers" value="Claude 3.5+, Claude Opus 4" good />
                  <CompatRow label="OS notes" value="macOS, Linux, Windows (WSL)" good />
                  <CompatRow label="Version constraint" value={`>= ${skill.version.split('.').slice(0,2).join('.')}.0`} />
                </div>
              </div>
            )}

            {tab === "trust" && (
              <div className="col gap-5">
                <SectionHead title="Trust & safety" />
                <div className="col gap-3">
                  <TrustRow icon="Verified" tone="blue" label="Author"
                    value={skill.author_verified ? `Verified · ${skill.author}` : `Unverified · ${skill.author}`}
                    good={skill.author_verified} />
                  <TrustRow icon="ShieldCheck" tone="green" label="Security review"
                    value={skill.badges.includes("secure") ? "Passed · 14 days ago" : "Not yet reviewed"}
                    good={skill.badges.includes("secure")} />
                  <TrustRow icon="Code" tone="iris" label="Source"
                    value={`github.com/${skill.author.replace(/[@/]/g,'').toLowerCase()}/${skill.id}`} />
                  <TrustRow icon="Lock" tone="amber" label="Permissions requested"
                    value={skill.permissions.join(" · ")} />
                  <TrustRow icon="Globe" tone="iris" label="Network access"
                    value={skill.permissions.find(p => p.toLowerCase().includes("network")) || "None"} />
                  <TrustRow icon="Folder" tone="iris" label="File system"
                    value={skill.permissions.find(p => /read|write/i.test(p)) || "Read uploaded files only"} />
                </div>
              </div>
            )}

            {tab === "reviews" && (
              <div className="col gap-4">
                <SectionHead title={`${skill.reviews} reviews`} subtitle={`Average rating ${skill.rating} / 5`} />
                {reviews.length === 0 ? (
                  <div className="card body-sm text-3" style={{ padding: 24 }}>No reviews surfaced yet for this skill.</div>
                ) : reviews.map((r, i) => (
                  <div key={i} className="card col gap-2" style={{ padding: 16 }}>
                    <div className="row between">
                      <div className="row gap-2">
                        <span className="avatar" style={{ width: 24, height: 24, fontSize: 10 }}>{r.user.slice(1,3).toUpperCase()}</span>
                        <div className="col">
                          <span style={{ font: "500 13px/1.2 var(--font-sans)" }}>{r.user}</span>
                          <span className="meta">{r.when}{r.verified_team && <> · <span style={{ color: "var(--iris-700)" }}>Workspace user</span></>}</span>
                        </div>
                      </div>
                      <Stars value={r.rating} />
                    </div>
                    <div className="body-sm" style={{ color: "var(--ink-1)" }}>{r.text}</div>
                  </div>
                ))}
              </div>
            )}

            {tab === "versions" && (
              <div className="col gap-4">
                <SectionHead title="Versions" />
                <div className="card col" style={{ padding: 0 }}>
                  {[
                    { v: skill.version, w: skill.last_updated, n: "Improved diff handling, faster on large repos.", current: true },
                    { v: prevVersion(skill.version, 1), w: "3 weeks ago", n: "Added rollback for partial failures." },
                    { v: prevVersion(skill.version, 2), w: "6 weeks ago", n: "Initial public release.", breaking: true },
                  ].map((v, i) => (
                    <div key={i} className="row gap-4" style={{
                      padding: 16, borderTop: i ? "1px solid var(--line-soft)" : "none",
                      alignItems: "flex-start",
                    }}>
                      <div className="col" style={{ width: 110, flex: "0 0 auto" }}>
                        <span className="mono" style={{ font: "500 13px/1.2 var(--font-mono)" }}>{v.v}</span>
                        <span className="meta">{v.w}</span>
                        {v.current && <span className="badge badge-team" style={{ marginTop: 6, alignSelf: "flex-start" }}>Current</span>}
                      </div>
                      <div className="col gap-2 grow">
                        <div className="body-sm" style={{ color: "var(--ink-1)" }}>{v.n}</div>
                        {v.breaking && <span className="badge badge-deprecated" style={{ alignSelf: "flex-start" }}>Breaking change</span>}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Related */}
            {related.length > 0 && (
              <section className="col gap-4">
                <SectionHead title="Works well with" subtitle="Skills frequently installed together." />
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
                  {related.map(s => (
                    <SkillCard key={s.id} skill={s} onOpen={onOpen} onInstall={onInstall} installed={installedSet.has(s.id)} dense />
                  ))}
                </div>
              </section>
            )}
          </main>

          {/* STICKY TRUST PANEL */}
          <aside style={{ position: "sticky", top: 80, alignSelf: "start" }}>
            <div className="card col" style={{ padding: 0, overflow: "hidden" }}>
              <div className="col gap-3" style={{ padding: 18, borderBottom: "1px solid var(--line-soft)" }}>
                {teamView && (
                  <div className="row gap-2" style={{
                    padding: "8px 10px", borderRadius: 8,
                    background: skill.team_approved ? "var(--green-50)" : "var(--amber-50)",
                    color: skill.team_approved ? "var(--green-700)" : "var(--amber-700)",
                    font: "500 12px/1.3 var(--font-sans)",
                  }}>
                    {skill.team_approved
                      ? <><I.ShieldCheck size={14} /> Approved for Acme · workspace-wide</>
                      : <><I.Clock size={14} /> Pending workspace approval</>
                    }
                  </div>
                )}
                <button className={`btn btn-lg ${installed ? "" : "btn-primary"}`} style={{ width: "100%", justifyContent: "center" }}
                  onClick={() => installed ? null : onInstall(skill)}>
                  {installed ? <><I.Check size={14} /> Installed in this workspace</> : <>Install — it's {skill.pricing.toLowerCase()}</>}
                </button>
                <div className="row gap-2">
                  <button className="btn" style={{ flex: 1, justifyContent: "center" }}><I.Bookmark size={14} /> Save</button>
                  <button className="btn" style={{ flex: 1, justifyContent: "center" }}><I.Share size={14} /> Share</button>
                </div>
                {teamView && !skill.team_approved && (
                  <button className="btn btn-accent" style={{ width: "100%", justifyContent: "center" }}>
                    Request workspace approval
                  </button>
                )}
              </div>

              <div className="col" style={{ padding: "8px 6px" }}>
                {trustItems.map((t, i) => (
                  <div key={t.label} className="row between" style={{ padding: "8px 12px", alignItems: "baseline" }}>
                    <span className="meta">{t.label}</span>
                    <span className="body-sm" style={{ color: "var(--ink-1)", textAlign: "right", maxWidth: 180 }}>{t.value}</span>
                  </div>
                ))}
              </div>

              <div className="col gap-2" style={{ padding: 14, borderTop: "1px solid var(--line-soft)", background: "var(--bg-soft)" }}>
                <div className="eyebrow">Permissions</div>
                {skill.permissions.map(p => (
                  <div key={p} className="row gap-2 body-sm" style={{ color: "var(--ink-2)" }}>
                    <I.Check size={12} style={{ color: "var(--green-600)", flex: "0 0 auto", marginTop: 4 }} />
                    <span>{p}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Why recommended */}
            <div className="card col gap-2" style={{ padding: 14, marginTop: 14 }}>
              <div className="eyebrow">Why we surfaced this</div>
              <ReasonChip icon="Trend">Trending this week</ReasonChip>
              <ReasonChip icon="Library">Works with tools in your library</ReasonChip>
              {teamView && skill.team_approved && <ReasonChip icon="Users">Team-approved in your workspace</ReasonChip>}
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}

function FactBlock({ title, items, tone, mono }) {
  if (!items || items.length === 0) return null;
  const tones = {
    green: { bullet: "var(--green-600)", bg: "var(--green-50)" },
    amber: { bullet: "var(--amber-600)", bg: "var(--amber-50)" },
  };
  const c = tones[tone] || { bullet: "var(--ink-3)", bg: "var(--bg-muted)" };
  return (
    <div className="card col gap-2" style={{ padding: 14 }}>
      <div className="eyebrow">{title}</div>
      <ul style={{ margin: 0, padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 6 }}>
        {items.map((it, i) => (
          <li key={i} className="row gap-2" style={{ alignItems: "flex-start" }}>
            <span style={{
              width: 5, height: 5, borderRadius: 999, background: c.bullet,
              marginTop: 8, flex: "0 0 auto",
            }} />
            <span className="body-sm" style={{ color: "var(--ink-1)", fontFamily: mono ? "var(--font-mono)" : "inherit", fontSize: mono ? 12.5 : 13 }}>{it}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

function PreviewBlock({ skill, tab, setTab, large }) {
  return (
    <div className="card col" style={{ padding: 0, overflow: "hidden" }}>
      <div className="row" style={{ background: "var(--bg-soft)", borderBottom: "1px solid var(--line)", padding: "0 4px" }}>
        {["Default", "Edge case"].map((t, i) => (
          <button key={t} className="unstyled"
            onClick={() => setTab(i)}
            style={{
              padding: "10px 14px",
              font: "500 12.5px/1 var(--font-sans)",
              color: tab === i ? "var(--ink)" : "var(--ink-3)",
              borderBottom: tab === i ? "2px solid var(--ink)" : "2px solid transparent",
              marginBottom: -1, cursor: "pointer",
            }}>{t}</button>
        ))}
      </div>
      <div className="col gap-3" style={{ padding: large ? 22 : 18 }}>
        <div className="col gap-1">
          <div className="eyebrow">Prompt</div>
          <div className="mono" style={{ background: "var(--bg-sunken)", padding: 12, borderRadius: 8, color: "var(--ink-1)" }}>
            {tab === 0 ? skill.sample_input : `Edge case: ${skill.sample_input}`}
          </div>
        </div>
        <div className="col gap-1">
          <div className="eyebrow">Output</div>
          <div style={{ background: "var(--bg-soft)", border: "1px solid var(--line-soft)", padding: 14, borderRadius: 8, color: "var(--ink-1)", font: "400 13.5px/1.55 var(--font-sans)", whiteSpace: "pre-wrap" }}>
            {skill.sample_output}
          </div>
        </div>
        <div className="row gap-2 meta" style={{ marginTop: 4 }}>
          <I.Pulse size={12} /> <span>Ran in 2.4s · model: Claude · cost: ~$0.003</span>
        </div>
      </div>
    </div>
  );
}

function CompatRow({ label, value, good }) {
  return (
    <div className="row between" style={{ padding: "10px 0", borderBottom: "1px solid var(--line-soft)" }}>
      <span className="meta" style={{ color: "var(--ink-2)" }}>{label}</span>
      <span className="row gap-2 body-sm" style={{ color: "var(--ink-1)" }}>
        {good && <I.Check size={12} style={{ color: "var(--green-600)" }} />}
        {value}
      </span>
    </div>
  );
}

function TrustRow({ icon, tone, label, value, good }) {
  const G = I[icon];
  const tones = {
    blue: ["var(--blue-50)", "var(--blue-700)"],
    green: ["var(--green-50)", "var(--green-700)"],
    amber: ["var(--amber-50)", "var(--amber-700)"],
    iris: ["var(--iris-50)", "var(--iris-700)"],
  }[tone] || ["var(--bg-muted)", "var(--ink-2)"];
  return (
    <div className="card row gap-3" style={{ padding: 14, alignItems: "flex-start" }}>
      <span style={{
        width: 28, height: 28, borderRadius: 7,
        background: tones[0], color: tones[1],
        display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto",
      }}><G size={14} /></span>
      <div className="col grow">
        <div className="row gap-2" style={{ alignItems: "baseline" }}>
          <span style={{ font: "500 13px/1.3 var(--font-sans)" }}>{label}</span>
          {good && <I.Check size={12} style={{ color: "var(--green-600)" }} />}
        </div>
        <div className="body-sm" style={{ color: "var(--ink-2)" }}>{value}</div>
      </div>
    </div>
  );
}

function prevVersion(v, back) {
  const parts = v.split(".").map(Number);
  parts[parts.length - 1] = Math.max(0, parts[parts.length - 1] - back);
  return parts.join(".");
}

window.DetailScreen = DetailScreen;
