function ClientDetail({ clientId, onClose, onStage, onNotesSave, clients }) {
  const src = clients || CLIENTS;
  const c = src.find(x => x.id === clientId);
  if (!c) return null;
  const calls = CALL_LOG[c.id] || [];
  const payments = PAYMENT_HISTORY[c.id] || [];
  const [notes, setNotes] = React.useState(c.notes || "");
  const [activeStage, setActiveStage] = React.useState(c.stage);
  const [linkCopied, setLinkCopied] = React.useState(false);
  const [showMore, setShowMore] = React.useState(false);

  // Keep notes in sync when switching clients
  React.useEffect(() => {
    setNotes(c.notes || "");
    setActiveStage(c.stage);
  }, [clientId]);

  function handleStageClick(key) {
    setActiveStage(key);
    if (onStage) onStage(c.id, key);
  }

  function handleNotesBlur() {
    if (onNotesSave) onNotesSave(c.id, notes);
  }

  function handleEmail() {
    window.open(`mailto:?subject=Your new website — ${c.name}&body=Hi there,%0A%0AI built a free website for ${c.name}. Take a look:%0A%0Ahttps://${c.siteUrl || "your-site.vercel.app"}%0A%0AHappy to hop on a quick call.`, "_blank");
  }

  function handleCopyLink() {
    const url = window.location.href.split("?")[0] + "?client=" + c.id;
    navigator.clipboard.writeText(url).catch(() => {});
    setLinkCopied(true);
    setTimeout(() => setLinkCopied(false), 1800);
  }

  return (
    <>
      <div className="cm-drawerScrim" onClick={onClose} />
      <aside className="cm-drawer" role="dialog" aria-label={c.name}>
        <div className="cm-drawer__bar">
          <span className="cm-drawer__id">{c.id}</span>
          <span style={{ color:"var(--color-ink-tertiary)" }}>·</span>
          <span className="cm-drawer__crumb">{c.name}</span>
          <div className="cm-drawer__bar-r" style={{ position:"relative" }}>
            <button className="cm-iconbtn" title={linkCopied ? "Copied!" : "Copy link"} onClick={handleCopyLink}>
              <i data-lucide={linkCopied ? "check" : "link"} className="cm-icon-xs"></i>
            </button>
              <button className="cm-iconbtn" title="More options" onClick={() => setShowMore(v => !v)}>
              <i data-lucide="more-horizontal" className="cm-icon-xs"></i>
            </button>
            {showMore && (
              <>
                <div style={{ position:"fixed", inset:0, zIndex:99 }} onClick={() => setShowMore(false)} />
                <div style={{ position:"absolute", right:0, top:"calc(100% + 4px)", background:"var(--color-surface-1)", border:"1px solid var(--color-hairline)", borderRadius:8, width:160, boxShadow:"0 8px 24px rgba(0,0,0,0.4)", zIndex:100, overflow:"hidden" }}>
                  {[
                    { icon:"trash-2", label:"Delete client", action:() => { if(confirm(`Delete ${c.name}?`)) { onClose(); } } },
                  ].map(item => (
                    <div key={item.label} onClick={() => { item.action(); setShowMore(false); }}
                      style={{ display:"flex", alignItems:"center", gap:8, padding:"8px 12px", fontSize:13, color:"var(--color-ink-muted)", cursor:"pointer" }}
                      onMouseEnter={e => e.currentTarget.style.background="var(--color-surface-2)"}
                      onMouseLeave={e => e.currentTarget.style.background="transparent"}>
                      <i data-lucide={item.icon} className="cm-icon-xs"></i>{item.label}
                    </div>
                  ))}
                </div>
              </>
            )}
            <button className="cm-iconbtn" onClick={onClose}><i data-lucide="x" className="cm-icon-sm"></i></button>
          </div>
        </div>

        <div className="cm-drawer__body">
          <div>
            <h2 className="cm-drawer__title">{c.name}</h2>
            <div className="cm-drawer__subtitle">{c.category} · {c.city}</div>
          </div>

          <div className="cm-drawer__quickRow">
            <button className="cm-btn cm-btn--primary" onClick={handleEmail}><i data-lucide="mail" className="cm-icon-xs"></i>Email</button>
            {c.siteUrl && <button className="cm-btn cm-btn--ghost" onClick={() => window.open("https://" + c.siteUrl, "_blank")}><i data-lucide="external-link" className="cm-icon-xs"></i>Open site</button>}
          </div>

          <div className="cm-section">
            <span className="cm-sectionHead">Stage</span>
            <div className="cm-stageBar">
              {STAGES.map(s => (
                <button key={s.key}
                        className={"cm-stageBar__b " + (s.key === activeStage ? "is-active" : "")}
                        onClick={() => handleStageClick(s.key)}>
                  <span className="cm-side__dot" style={{ background: s.color, marginRight: 6, display:"inline-block", verticalAlign:"middle" }} />
                  {s.label}
                </button>
              ))}
            </div>
          </div>

          <div className="cm-section">
            <span className="cm-sectionHead">Business info</span>
            <div className="cm-kvs">
              <div className="cm-kv"><span className="cm-kv__k">Phone</span><span className="cm-kv__v cm-mono">{c.phone}</span></div>
              <div className="cm-kv"><span className="cm-kv__k">Category</span><span className="cm-kv__v">{c.category}</span></div>
              <div className="cm-kv"><span className="cm-kv__k">Google rating</span><span className="cm-kv__v"><i data-lucide="star" className="cm-icon-xs" style={{ color:"#f2c94c", marginRight:4 }}></i>{c.rating} <span style={{ color:"var(--color-ink-subtle)" }}>({c.reviews})</span></span></div>
              <div className="cm-kv"><span className="cm-kv__k">Location</span><span className="cm-kv__v">{c.city}</span></div>
            </div>
          </div>

          <div className="cm-section">
            <span className="cm-sectionHead">Site</span>
            <div className="cm-kvs">
              <div className="cm-kv"><span className="cm-kv__k">Vercel URL</span><span className="cm-kv__v cm-mono">{c.siteUrl || "—"}</span></div>
              <div className="cm-kv"><span className="cm-kv__k">Status</span><span className="cm-kv__v">{c.live ? <span className="cm-tag cm-tag--ok">Live</span> : <span className="cm-tag">Not deployed</span>}</span></div>
              <div className="cm-kv"><span className="cm-kv__k">Built</span><span className="cm-kv__v">{c.built || "—"}</span></div>
              <div className="cm-kv"><span className="cm-kv__k">Deployed</span><span className="cm-kv__v">{c.deployed || "—"}</span></div>
            </div>
          </div>

          {calls.length > 0 && (
            <div className="cm-section">
              <span className="cm-sectionHead">Call log</span>
              <div>
                {calls.map((call, i) => (
                  <div key={i} className="cm-callRow">
                    <span className="cm-callRow__date">{call.date}</span>
                    <span className="cm-callRow__time">{call.time}<br/>{call.duration}</span>
                    <span className="cm-callRow__outcome">
                      <span className="cm-side__dot" style={{ background:
                        call.outcome === "Closed"   ? "#3bbdb1" :
                        call.outcome === "Renewed"  ? "#3bbdb1" :
                        call.outcome === "Pitched"  ? "#bb87fc" :
                        call.outcome === "Negotiating" ? "#eb7235" :
                        "#8a8f98" }} />
                      {call.outcome}
                    </span>
                    <span className="cm-callRow__notes">{call.notes}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {payments.length > 0 && (
            <div className="cm-section">
              <span className="cm-sectionHead">Payment history</span>
              <div>
                {payments.map((p, i) => (
                  <div key={i} className="cm-payRow">
                    <span className="cm-callRow__date">{p.date}</span>
                    <span className="cm-payRow__meth">{p.method}</span>
                    <span className="cm-payRow__amt">${p.amount}</span>
                  </div>
                ))}
                {c.nextPayment && (
                  <div className="cm-payRow">
                    <span className="cm-callRow__date" style={{ color:"var(--color-ink-subtle)" }}>{c.nextPayment}</span>
                    <span className="cm-payRow__meth">Upcoming · Stripe auto-charge</span>
                    <span className="cm-payRow__amt" style={{ color:"var(--color-ink-subtle)" }}>${c.mrr}</span>
                  </div>
                )}
              </div>
            </div>
          )}

          <div className="cm-section">
            <span className="cm-sectionHead">Notes</span>
            <textarea className="cm-textarea"
              value={notes}
              onChange={e => setNotes(e.target.value)}
              onBlur={handleNotesBlur}
              placeholder="Add a note..." />
          </div>
        </div>
      </aside>
    </>
  );
}
window.ClientDetail = ClientDetail;
