/* =========================================================================
   Live ICP Tracker — Account Command Card (internal deep record)
   Exports: CommandCard
   ========================================================================= */
const { useState, useEffect } = React;
function Field({ k, v, src }) {
  return (
    <div className="field">
      <span className="k">{k}</span>
      <span className="v">{v}</span>
      {src && <span className="src">via {src}</span>}
    </div>
  );
}

function ScoreBreakdown({ a }) {
  const I = window.ICP;
  const W = I.WEIGHTS, M = I.WEIGHT_META, c = a.components;
  const rows = ["revenueFit", "vendorVuln", "trafficScale", "catalogFit", "signalHeat", "warmPath", "strategicFit"];
  return (
    <div>
      {rows.map(key => {
        const contrib = Math.round(W[key] * c[key]);
        const pct = (contrib / W[key]) * 100;
        return (
          <div className="hbar" key={key}>
            <span className="lab">{M[key].label}</span>
            <div className="track"><i style={{ width: pct + "%", background: pct >= 70 ? "var(--c-malachyte)" : "var(--c-malachyte-light)" }}></i></div>
            <span className="pv">{contrib}/{W[key]}</span>
          </div>
        );
      })}
      {c.negative > 0 && (
        <div className="hbar">
          <span className="lab" style={{ color: "var(--st-danger)" }}>Negative signals</span>
          <div className="track"><i style={{ width: (c.negative * 100) + "%", background: "var(--st-danger)" }}></i></div>
          <span className="pv">−{Math.round(W.negative * c.negative)}</span>
        </div>
      )}
    </div>
  );
}

function RequestIntroModal({ account: a, onClose }) {
  const [desc, setDesc] = useState("");
  const [done, setDone] = useState(false);
  const [saving, setSaving] = useState(false);
  useEffect(() => {
    function onEsc(e) { if (e.key === "Escape") onClose(); }
    document.addEventListener("keydown", onEsc);
    return () => document.removeEventListener("keydown", onEsc);
  }, [onClose]);

  const submit = async () => {
    setSaving(true);
    setDone(true); // optimistic
    try {
      await fetch("/api/referrals", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ kind: "account", accountId: a.id, accountName: a.brand, description: desc }),
      });
    } catch (e) { console.log("[v0] request intro failed:", e && e.message); }
    finally { setSaving(false); }
  };

  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" role="dialog" aria-label="Request intro">
        {done ? (
          <>
            <div className="modal-body" style={{ textAlign: "center", padding: "28px 24px" }}>
              <div className="intro-check"><Icon name="check" size={22} /></div>
              <h3 style={{ marginTop: 12 }}>Intro requested</h3>
              <p className="subtle" style={{ marginTop: 6 }}>Your warm-intro request for <b>{a.brand}</b> has been posted to the roster.</p>
            </div>
            <div className="modal-foot" style={{ justifyContent: "center" }}>
              <button className="btn sm pri" onClick={onClose}>Done</button>
            </div>
          </>
        ) : (
          <>
            <div className="modal-head">
              <h3>Request intro to {a.brand}</h3>
              <button className="btn ghost sm" onClick={onClose} aria-label="Close"><Icon name="x" size={16} /></button>
            </div>
            <div className="modal-body">
              <p className="subtle" style={{ marginBottom: 14 }}>
                Post a warm-intro request for <b>{a.brand}</b> to the team roster. Add an optional note for whoever picks it up.
              </p>
              <div className="filter-field">
                <label>Description <span className="subtle" style={{ fontWeight: 400 }}>(optional)</span></label>
                <textarea className="modal-input" rows={4} autoFocus
                  placeholder="e.g. Looking for a warm path to their Head of Ecommerce — happy to brief whoever connects us."
                  value={desc} onChange={e => setDesc(e.target.value)}
                  style={{ resize: "vertical", lineHeight: 1.5 }} />
              </div>
            </div>
            <div className="modal-foot">
              <button className="btn sm ghost" onClick={onClose}>Cancel</button>
              <button className="btn sm pri" onClick={submit}><Icon name="users" size={14} />Request intro</button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function CommandCard({ account: a, onBack }) {
  const I = window.ICP;
  const [showIntro, setShowIntro] = useState(false);
  return (
    <div className="page">
      {/* breadcrumb + actions */}
      <div className="between" style={{ marginBottom: 16 }}>
        <button className="btn ghost sm" onClick={onBack}><Icon name="chevL" size={15} />Back to list</button>
      </div>

      {/* header */}
      <div className="card pad" style={{ marginBottom: 16 }}>
        <div className="row gap16" style={{ alignItems: "flex-start" }}>
          <Logo name={a.brand} src={a.logo} size="lg" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="between gap10" style={{ alignItems: "flex-start" }}>
              <div className="row gap10 wrap" style={{ alignItems: "center" }}>
                <h2 style={{ fontSize: 24 }}>{a.brand}</h2>
                <Tier t={a.tier} />
                <StatusChip status={a.engagement.status} />
              </div>
              <button className="btn pri sm" style={{ flex: "none" }} onClick={() => setShowIntro(true)}>
                <Icon name="users" size={14} />Request intro
              </button>
            </div>
            <div className="muted mt4">{a.vertical} · {a.parent} · <span className="mono">{a.domain}</span></div>
            <div className="row gap16 wrap mt12">
              <div className="field"><span className="k">ICP score</span><span className="v" style={{ fontSize: 22, color: "var(--c-malachyte)" }}>{a.score}<span className="subtle" style={{ fontSize: 13 }}>/100</span></span></div>
              <div className="field"><span className="k">Online revenue</span><span className="v" style={{ fontSize: 16 }}>{I.fmtMoney(a.onlineRev)}</span></div>
              <div className="field"><span className="k">Malachyte impact</span><span className="v" style={{ fontSize: 16, color: "var(--c-malachyte-dark)" }}>${a.impact.low}M–${a.impact.high}M<span className="subtle" style={{ fontWeight: 400, fontSize: 12 }}> /yr</span></span></div>
              <div className="field"><span className="k">Owner</span><span className="v" style={{ fontSize: 16 }}>{a.engagement.owner}</span></div>
              <div className="field"><span className="k">Next step</span><span className="v" style={{ fontSize: 14 }}>{a.engagement.next}</span></div>
            </div>
          </div>
        </div>
      </div>

      <div className="detail-grid">
        {/* LEFT column */}
        <div className="col gap16">
          {/* Firmographics */}
          <div className="card pad">
            <div className="label-micro" style={{ marginBottom: 14 }}>Firmographics & financial picture</div>
            <div className="fields">
              <Field k="Online revenue" v={I.fmtMoney(a.onlineRev)} src="SimilarWeb formula" />
              <Field k="Est. ARR" v={I.fmtMoney(a.arr)} src="The Org" />
              <Field k="Monthly visits" v={a.visits + "M"} src="SimilarWeb" />
              <Field k="SKU count" v={a.sku.toLocaleString()} src="BuiltWith" />
              <Field k="Headcount" v={a.employees.toLocaleString()} src="LinkedIn" />
              <Field k="Parent company" v={a.parent.split("(")[0].trim()} src="The Org" />
            </div>
          </div>

          {/* Tech stack */}
          <div className="card pad">
            <div className="between" style={{ marginBottom: 12 }}>
              <span className="label-micro">Competing tech stack</span>
              <span className="subtle" style={{ fontSize: 11 }}>BuiltWith · weekly refresh</span>
            </div>
            <table className="tbl" style={{ fontSize: 13 }}>
              <thead><tr><th>Vendor</th><th>Category</th><th>First detected</th><th>Status</th></tr></thead>
              <tbody>
                {a.vendors.map((v, i) => (
                  <tr key={i} style={{ cursor: "default" }}>
                    <td style={{ fontWeight: 500 }}>{v.name}</td>
                    <td className="muted">{v.category}</td>
                    <td className="mono muted">{v.since}</td>
                    <td>{v.status === "expiring"
                      ? <span className="chip" style={{ background: "rgba(216,146,81,0.14)", color: "#9A5B1E" }}><span className="dot" style={{ background: "var(--c-sunset)" }}></span>renewal window</span>
                      : <span className="chip"><span className="dot" style={{ background: "var(--c-malachyte)" }}></span>active</span>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* People map */}
          <div className="card pad">
            <div className="between" style={{ marginBottom: 8 }}>
              <span className="label-micro">People Map</span>
              <span className="subtle" style={{ fontSize: 11 }}>LinkedIn + The Org</span>
            </div>
            {a.people.map((p, i) => (
              <div className="person" key={i}>
                <Avatar name={p.name} />
                <div className="meta">
                  <div className="nm">{p.name}</div>
                  <div className="tt">{p.title}</div>
                </div>
                <span className="chip">{p.role}</span>
                {p.warm && <span className="chip" style={{ background: "var(--bg-accent-soft)", color: "var(--c-malachyte-dark)" }}><Icon name="link" size={11} />warm</span>}
              </div>
            ))}
          </div>
        </div>

        {/* RIGHT column */}
        <div className="col gap16">
          {/* Score breakdown */}
          <div className="card pad">
            <div className="between" style={{ marginBottom: 10 }}>
              <span className="label-micro">ICP score breakdown</span>
              <span className="score-num" style={{ fontSize: 18, color: "var(--c-malachyte)" }}>{a.score}</span>
            </div>
            <ScoreBreakdown a={a} />
            <button className="btn sm mt12" style={{ width: "100%" }}><Icon name="sliders" size={14} />Tune weights</button>
          </div>

          {/* Warm intro */}
          <div className="card pad">
            <div className="label-micro" style={{ marginBottom: 10 }}>Best warm-intro path</div>
            {a.warmIntro.degree > 0 ? (
              <div>
                <div className="row gap10">
                  <Avatar name={a.warmIntro.introducer} />
                  <div>
                    <div style={{ fontWeight: 500 }}>{a.warmIntro.introducer}</div>
                    <div className="subtle" style={{ fontSize: 11.5 }}>{a.warmIntro.strength}</div>
                  </div>
                </div>
                <div className="hyp mt12" style={{ fontSize: 12.5 }}>{a.warmIntro.via}</div>
                <div className="row gap8 mt12">
                  <div className="bar" style={{ flex: 1 }}><i style={{ width: (a.warmIntro.degree * 10) + "%" }}></i></div>
                  <span className="subtle" style={{ fontSize: 11 }}>strength {a.warmIntro.degree}/10</span>
                </div>
                <button className="btn pri sm mt12" style={{ width: "100%" }}><Icon name="users" size={14} />Request intro via {a.warmIntro.introducer.split(" ")[0]}</button>
              </div>
            ) : (
              <div className="empty" style={{ padding: 18 }}>
                <Icon name="users" size={20} style={{ color: "var(--fg-subtle)", marginBottom: 6 }} />
                <div style={{ fontSize: 12.5 }}>No warm path found yet.<br />Run network graph traversal.</div>
                <button className="btn sm mt12"><Icon name="refresh" size={13} />Find a path</button>
              </div>
            )}
          </div>

          {/* Signal feed */}
          <div className="card pad">
            <div className="between" style={{ marginBottom: 6 }}>
              <span className="label-micro">Live signals</span>
              <span className="subtle" style={{ fontSize: 11 }}>last 90 days</span>
            </div>
            {a.signals.length ? a.signals.map((s, i) => (
              <div className="signal" key={i}>
                <SignalIcon type={s.type} heat={s.heat} />
                <div className="stx">
                  <div style={{ fontSize: 12.5, lineHeight: 1.4 }}>{s.text}</div>
                </div>
                <span className="when">{s.date}</span>
              </div>
            )) : <div className="empty" style={{ padding: 14, fontSize: 12 }}>No recent signals</div>}
          </div>

          {/* Engagement */}
          <div className="card pad">
            <div className="label-micro" style={{ marginBottom: 12 }}>Engagement (HubSpot sync)</div>
            <div className="col gap10">
              <div className="between"><span className="subtle">Lifecycle stage</span><span style={{ fontWeight: 500 }}>{a.engagement.stage}</span></div>
              <div className="between"><span className="subtle">Last touch</span><span style={{ fontWeight: 500 }}>{a.engagement.lastTouch}</span></div>
              <div className="between"><span className="subtle">Status</span><StatusChip status={a.engagement.status} /></div>
              <div className="between"><span className="subtle">Referral spend</span><span style={{ fontWeight: 500 }}>${(a.spend.meetings * a.spend.perMeeting).toLocaleString()}</span></div>
            </div>
          </div>
        </div>
      </div>

      {showIntro && <RequestIntroModal account={a} onClose={() => setShowIntro(false)} />}
    </div>
  );
}

Object.assign(window, { CommandCard });
