/* global React, Icon, Button, Chip, AgentAvatar, PROV_META */
const { useState: useBits } = React;

const TONES = {
  cardinal: { color: "#8C1515", tint: "#F9E9EA", line: "#ECC9CB", text: "#5E0E0E" },
  sage:     { color: "#5A7150", tint: "#E4EAE0", line: "#B5C2AB", text: "#2F4528" },
  slate:    { color: "#4A5868", tint: "#E1E5E9", line: "#B4BFCB", text: "#2A3744" },
  ochre:    { color: "#B08A3E", tint: "#F2E9D2", line: "#DCC799", text: "#6E5419" },
  neutral:  { color: "#5C544A", tint: "rgba(31,27,22,0.05)", line: "#E8E2D5", text: "#3A332B" },
};

// ---- Card surface ----
const Panel = ({ children, pad = 20, accent, style = {}, className = "" }) => (
  <div className={className} style={{
    background: "#fff", border: "1px solid rgba(31,27,22,0.08)", borderRadius: 10,
    boxShadow: "0 1px 2px rgba(31,27,22,0.04)", position: "relative",
    padding: pad, ...style,
  }}>
    {accent && <span style={{ position: "absolute", left: 0, top: 16, bottom: 16, width: 2, background: accent, borderRadius: 2 }}/>}
    {children}
  </div>
);

// ---- Screen header: eyebrow + Fraunces title + lede + actions ----
const ScreenHeader = ({ eyebrow, title, lede, actions, step }) => (
  <div style={{ marginBottom: 22, display: "flex", alignItems: "flex-start", gap: 20 }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      {eyebrow && <div className="cd-eyebrow" style={{ marginBottom: 8 }}>{eyebrow}</div>}
      <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 32, letterSpacing: "-0.02em", lineHeight: 1.05, margin: 0 }}>{title}</h2>
      {lede && <p style={{ fontFamily: "var(--font-display)", fontSize: 18, lineHeight: 1.4, color: "var(--fg-2)", margin: "10px 0 0", maxWidth: 640 }}>{lede}</p>}
    </div>
    {actions && <div style={{ display: "flex", gap: 8, flexShrink: 0, paddingTop: 4 }}>{actions}</div>}
  </div>
);

const SectionLabel = ({ children, style = {} }) => (
  <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-2)", ...style }}>{children}</div>
);

// ---- Offerroom inline note ----
const AgentNote = ({ children, working = false, time = "now", actions }) => (
  <div style={{ display: "flex", gap: 12, alignItems: "flex-start", background: "rgba(140,21,21,0.035)", border: "1px solid rgba(140,21,21,0.10)", borderRadius: 10, padding: "13px 15px" }}>
    <AgentAvatar working={working} size={26}/>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: 11, color: "var(--fg-2)", marginBottom: 3 }}>
        <b style={{ color: "var(--fg-1)", fontWeight: 600 }}>Offerroom</b> · {time}
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.55, color: "var(--fg-1)" }}>{children}</div>
      {actions && <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>{actions}</div>}
    </div>
  </div>
);

// ---- Provenance chip + hover trail (the signature feature) ----
const ProvBadge = ({ db, small }) => {
  const m = PROV_META[db] || PROV_META.Vault;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5, flexShrink: 0,
      padding: small ? "1px 7px" : "2px 8px", borderRadius: 999,
      background: m.tint, color: m.color, fontSize: small ? 10 : 11, fontWeight: 600,
      fontFamily: "var(--font-mono)", letterSpacing: "0.02em",
    }}>
      <span style={{ width: 5, height: 5, borderRadius: 999, background: m.color }}/>{m.label}
    </span>
  );
};

// Hover-to-reveal provenance. `trail` = [{db,label,detail}], renders a tethered popover.
const Provenance = ({ children, trail = [] }) => {
  const [open, setOpen] = useBits(false);
  return (
    <span style={{ position: "relative" }}
      onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <span className="prov-target">{children}</span>
      {open && (
        <span className="cad-fade" style={{
          position: "absolute", left: 0, bottom: "calc(100% + 8px)", zIndex: 40,
          width: 320, background: "#fff", border: "1px solid rgba(31,27,22,0.12)",
          borderRadius: 10, boxShadow: "0 16px 40px rgba(31,27,22,0.16)", padding: 12,
          display: "block", textAlign: "left", whiteSpace: "normal", cursor: "default",
        }}>
          <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--fg-2)", marginBottom: 10 }}>
            How Offerroom built this
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {trail.map((s, i) => (
              <div key={i} style={{ display: "flex", gap: 10, paddingBottom: i < trail.length - 1 ? 12 : 0, position: "relative" }}>
                <div style={{ flexShrink: 0, display: "flex", flexDirection: "column", alignItems: "center" }}>
                  <ProvBadge db={s.db} small/>
                  {i < trail.length - 1 && <span style={{ width: 1, flex: 1, minHeight: 14, background: "var(--ink-100)", marginTop: 4 }}/>}
                </div>
                <div style={{ minWidth: 0, paddingTop: 1 }}>
                  <div style={{ fontSize: 12, fontWeight: 500, color: "var(--fg-1)", lineHeight: 1.35 }}>{s.label}</div>
                  {s.detail && <div style={{ fontSize: 11, color: "var(--fg-2)", marginTop: 2, lineHeight: 1.4 }}>{s.detail}</div>}
                </div>
              </div>
            ))}
          </div>
        </span>
      )}
    </span>
  );
};

// ---- Fit score badge ----
const FitBadge = ({ value, size = "md" }) => {
  const pct = Math.round(value * 100);
  const tone = value >= 0.85 ? "sage" : value >= 0.75 ? "slate" : "ochre";
  const t = TONES[tone];
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: size === "sm" ? "2px 8px" : "3px 10px", borderRadius: 999,
      background: t.tint, color: t.text, fontSize: size === "sm" ? 11 : 12, fontWeight: 600,
      fontVariantNumeric: "tabular-nums",
    }}>
      <span style={{ width: 6, height: 6, borderRadius: 999, background: t.color }}/>
      {value.toFixed(2)} fit
    </span>
  );
};

// ---- Segmented control ----
const Segmented = ({ options, value, onChange }) => (
  <div style={{ display: "inline-flex", background: "var(--paper-sunken)", border: "1px solid var(--ink-100)", borderRadius: 8, padding: 3, gap: 2 }}>
    {options.map(o => {
      const active = o.value === value;
      return (
        <button key={o.value} onClick={() => onChange(o.value)} style={{
          padding: "6px 14px", borderRadius: 6, border: "none", cursor: "pointer",
          fontSize: 13, fontWeight: 500, fontFamily: "var(--font-sans)",
          background: active ? "#fff" : "transparent",
          color: active ? "var(--fg-1)" : "var(--fg-2)",
          boxShadow: active ? "0 1px 2px rgba(31,27,22,0.06)" : "none",
          transition: "all 120ms cubic-bezier(0.2,0.7,0.1,1)",
        }}>{o.label}</button>
      );
    })}
  </div>
);

// ---- Upload dropzone ----
const Dropzone = ({ icon = "upload", title, sub, tall = false, onClick }) => (
  <button onClick={onClick} style={{
    width: "100%", border: "1.5px dashed rgba(31,27,22,0.18)", borderRadius: 12,
    background: "rgba(31,27,22,0.015)", padding: tall ? "40px 24px" : "24px",
    display: "flex", flexDirection: "column", alignItems: "center", gap: 10,
    cursor: "pointer", textAlign: "center", fontFamily: "var(--font-sans)",
    transition: "background 120ms, border-color 120ms",
  }}
    onMouseEnter={e => { e.currentTarget.style.background = "rgba(140,21,21,0.04)"; e.currentTarget.style.borderColor = "rgba(140,21,21,0.30)"; }}
    onMouseLeave={e => { e.currentTarget.style.background = "rgba(31,27,22,0.015)"; e.currentTarget.style.borderColor = "rgba(31,27,22,0.18)"; }}>
    <span style={{ width: 44, height: 44, borderRadius: 999, background: "#fff", border: "1px solid var(--ink-100)", display: "grid", placeItems: "center", color: "var(--cardinal)" }}>
      <Icon name={icon} size={20}/>
    </span>
    <div style={{ fontSize: 15, fontWeight: 500, color: "var(--fg-1)" }}>{title}</div>
    {sub && <div style={{ fontSize: 12.5, color: "var(--fg-2)", maxWidth: 320, lineHeight: 1.45 }}>{sub}</div>}
  </button>
);

// ---- Progress steps (for the tailor flow) ----
const StepRail = ({ steps, current, onJump }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 0 }}>
    {steps.map((s, i) => {
      const done = i < current, active = i === current;
      return (
        <React.Fragment key={s.key}>
          <button onClick={() => onJump && onJump(i)} style={{
            display: "flex", alignItems: "center", gap: 8, background: "transparent", border: "none",
            cursor: "pointer", padding: "4px 2px", fontFamily: "var(--font-sans)",
          }}>
            <span style={{
              width: 22, height: 22, borderRadius: 999, flexShrink: 0,
              display: "grid", placeItems: "center", fontSize: 11, fontWeight: 600,
              background: active ? "#8C1515" : done ? "#5A7150" : "#fff",
              color: active || done ? "#fff" : "var(--fg-2)",
              border: active || done ? "1px solid transparent" : "1px solid var(--ink-100)",
            }}>{done ? <Icon name="check" size={12}/> : i + 1}</span>
            <span style={{ fontSize: 13, fontWeight: active ? 600 : 500, color: active ? "var(--fg-1)" : "var(--fg-2)", whiteSpace: "nowrap" }}>{s.label}</span>
          </button>
          {i < steps.length - 1 && <span style={{ width: 24, height: 1, background: "var(--ink-100)", margin: "0 8px", flexShrink: 0 }}/>}
        </React.Fragment>
      );
    })}
  </div>
);

// ---- Toolbar over a document preview ----
const DocToolbar = ({ left, right }) => (
  <div style={{
    display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
    padding: "10px 14px", borderBottom: "1px solid var(--ink-100)", background: "var(--paper)",
    borderTopLeftRadius: 10, borderTopRightRadius: 10,
  }}>
    <div style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>{left}</div>
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>{right}</div>
  </div>
);

const Pill = ({ children, tone = "neutral" }) => {
  const t = TONES[tone] || TONES.neutral;
  return <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 10px", borderRadius: 999, background: t.tint, color: t.text, fontSize: 11.5, fontWeight: 600 }}>{children}</span>;
};

Object.assign(window, { TONES, Panel, ScreenHeader, SectionLabel, AgentNote, ProvBadge, Provenance, FitBadge, Segmented, Dropzone, StepRail, DocToolbar, Pill });
