// LeadDetail.jsx — one data-driven detail page that works for any lead.
// Reads buildDetail(lead) and swaps type-specific content: a type badge, a
// phase chip (pre-claim only), the right key-data, signals, activity, the
// coverage hero (need / gap / recommended), and the left-rail anchor field.
// The primary action stays a single shared "Generate Automated Campaign".

// ----------------------------------------------------------------- left rail
const DetailNav = ({ onBack }) => (
  <div style={{ position: "relative", width: "100%", height: 54, flexShrink: 0, display: "flex", alignItems: "center", padding: "0 24px", borderBottom: "1px solid var(--helm-dark-ecru)", background: "var(--helm-white)", zIndex: 1 }}>
    <div onClick={() => onBack && onBack()} style={{ display: "flex", alignItems: "center", gap: 12, cursor: onBack ? "pointer" : "default" }}>
      <img src="helm/logo/bannerlife-logo.png" alt="Banner Life" style={{ height: 20, display: "block" }} />
      <div style={{ width: 1, height: 20, background: "var(--helm-dark-ecru)" }} />
      <img src="helm/logo/helm-logotype-darkgreen.svg" alt="Helm" style={{ height: 17, display: "block" }} />
      <span style={{ fontFamily: "var(--font-serif)", fontSize: 15, color: "var(--helm-dark-green)", whiteSpace: "nowrap" }}>Producer Co-pilot</span>
    </div>
    <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 18, fontSize: 13 }}>
      {["Leads", "Campaigns", "Reports"].map((item) => (
        <button key={item} onClick={() => item === "Leads" && onBack && onBack()} style={{ background: "transparent", border: "none", padding: "4px 2px", cursor: item === "Leads" && onBack ? "pointer" : "default", fontFamily: "var(--font-sans)", fontSize: 13, fontWeight: 500, color: "var(--helm-dark-grey)" }}>{item}</button>
      ))}
      {window.ProfileMenu ? (
        <window.ProfileMenu initials="MP" bg="var(--helm-dark-green)" fg="var(--helm-white)" size={30}
          name="Morgan Pierce" subtitle="Producer" style={{ marginLeft: 4 }} />
      ) : (
        <div style={{ width: 30, height: 30, borderRadius: "50%", background: "var(--helm-dark-green)", color: "var(--helm-white)", display: "grid", placeItems: "center", fontWeight: 600, fontSize: 12, marginLeft: 4 }}>MP</div>
      )}
    </div>
  </div>
);

const TypeBadge = ({ type }) => {
  const m = CP_TYPE_META[type];
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8, height: 26, padding: "0 12px", borderRadius: 13, background: m.bg, whiteSpace: "nowrap" }}>
      <span style={{ width: 7, height: 7, borderRadius: 1, background: m.color, transform: "rotate(45deg)", flexShrink: 0 }} />
      <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 12.5, color: "var(--helm-dark-green)" }}>{m.label}</span>
    </span>
  );
};

const SendIcon = () => <svg width="14" height="14" viewBox="0 0 24 24" fill="var(--helm-white)"><path d="M2 21V14l9-2-9-2V3l20 9z" /></svg>;
const PhoneIcon = () => <svg width="14" height="14" viewBox="0 0 24 24" fill="var(--helm-white)"><path d="M20 17.5c-1.2 0-2.5-.2-3.6-.6-.3-.1-.7 0-1 .2l-2.2 2.2c-2.8-1.4-5.1-3.8-6.6-6.6l2.2-2.2c.3-.3.4-.7.2-1C8.4 8.5 8.2 7.2 8.2 6c0-.6-.4-1-1-1H4c-.6 0-1 .4-1 1 0 9.4 7.6 17 17 17 .6 0 1-.4 1-1v-3.5c0-.6-.4-1-1-1z" /></svg>;
const EditIcon = () => <svg width="13" height="13" viewBox="0 0 24 24" fill="var(--helm-white)"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z" /></svg>;

const Field = ({ label, value, action }) => (
  <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--helm-dark-grey)", marginBottom: 3 }}>{label}</div>
      <div style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 14, lineHeight: "19px", color: "var(--helm-dark-green)" }}>{value}</div>
    </div>
    {action && (
      <div style={{ width: 28, height: 28, borderRadius: "50%", background: "var(--helm-dark-ecru)", display: "grid", placeItems: "center", flexShrink: 0, opacity: 0.7 }}>
        {action === "send" && <SendIcon />}{action === "phone" && <PhoneIcon />}{action === "edit" && <EditIcon />}
      </div>
    )}
  </div>
);

const GenerateCampaignButton = ({ onClick }) => (
  <button onClick={onClick} style={{ position: "relative", width: "100%", minHeight: 48, flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", gap: 9, padding: "10px 16px", lineHeight: 1.2, background: "var(--helm-chartreuse-2)", color: "var(--helm-white)", border: "none", borderRadius: 24, fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14, cursor: "pointer", transition: "transform 80ms ease" }}
    onMouseDown={(e) => { e.currentTarget.style.transform = "translateY(1px)"; }}
    onMouseUp={(e) => { e.currentTarget.style.transform = "none"; }}
    onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; }}>
    <span className="helm-star" style={{ width: 17, height: 17, flexShrink: 0 }} />
    Generate Automated Campaign
  </button>
);

const DetailLeftRail = ({ lead, detail, onGenerateCampaign }) => (
  <div style={{ width: "clamp(330px, 30%, 420px)", flexShrink: 0, background: "linear-gradient(rgba(254,252,245,0.6),rgba(254,252,245,0.6)), var(--helm-ecru)", borderRight: "1px solid var(--helm-dark-ecru)", padding: "32px clamp(24px, 3vw, 56px)", display: "flex", flexDirection: "column", gap: 18 }}>
    <LeadAvatar lead={lead} size={56} radius={14} />
    <TypeBadge type={lead.type} />
    <h1 style={{ fontFamily: "var(--font-serif)", fontWeight: 600, fontSize: 40, lineHeight: "42px", margin: 0, color: "var(--helm-dark-green)", letterSpacing: "-0.01em" }}>{lead.name}</h1>

    {detail.phase && (
      <div style={{ display: "flex", flexDirection: "column", gap: 7, padding: "12px 14px", borderRadius: 14, background: detail.phase.bg, border: `1px solid ${detail.phase.color}` }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ width: 8, height: 8, borderRadius: "50%", background: detail.phase.dot }} />
          <span style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 13, color: "var(--helm-dark-green)", whiteSpace: "nowrap" }}>{detail.phase.label}</span>
        </div>
        <div style={{ fontFamily: "var(--font-sans)", fontSize: 12.5, lineHeight: "17px", color: "var(--helm-dark-green)", opacity: 0.82 }}>{detail.phase.desc}</div>
      </div>
    )}

    {onGenerateCampaign && <GenerateCampaignButton onClick={onGenerateCampaign} />}

    <div style={{ display: "flex", flexDirection: "column", gap: 13, marginTop: 4 }}>
      <Field label="Legal name" value={lead.contact.legal} />
      <Field label="Email" value={lead.contact.email} action="send" />
      <Field label="Phone" value={lead.contact.phone} action="phone" />
      <Field label="Address" value={<>{lead.contact.street}<br />{lead.contact.city}</>} />
      <div style={{ borderTop: "1px solid var(--helm-dark-ecru)", margin: "2px 0" }} />
      <Field label={detail.anchor.label} value={<>{detail.anchor.value}{detail.anchor.sub && <><br /><span style={{ fontWeight: 400, color: "var(--helm-dark-grey)", fontSize: 12 }}>{detail.anchor.sub}</span></>}</>} action={detail.anchor.action} />
      <div style={{ borderTop: "1px solid var(--helm-dark-ecru)", margin: "2px 0" }} />
      <Field label="Notes" value={detail.notes} action="edit" />
    </div>
  </div>
);

// ----------------------------------------------------------------- middle cards
const InfoCard = ({ children, style }) => (
  <div style={{ background: "var(--helm-white)", border: "1px solid var(--helm-dark-ecru)", borderRadius: 16, padding: "18px 20px", boxShadow: "0 1px 2px rgba(0,29,0,0.03), 0 14px 30px -18px rgba(0,29,0,0.20)", ...style }}>{children}</div>
);

const CardTitle = ({ children, accent }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
    <span style={{ width: 7, height: 7, background: accent, transform: "rotate(45deg)", borderRadius: 1, flexShrink: 0 }} />
    <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 16, lineHeight: "20px", color: "var(--helm-dark-green)", margin: 0 }}>{children}</h3>
  </div>
);

const ScoreRing = ({ score, caption }) => {
  const tier = CP_scoreTier(score);
  const c = 2 * Math.PI * 42;
  const dash = (score / 100) * c;
  return (
    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flexShrink: 0 }}>
      <div style={{ width: 128, height: 128, position: "relative" }}>
        <svg viewBox="0 0 100 100" width="128" height="128" style={{ position: "absolute", inset: 0 }}>
          <circle cx="50" cy="50" r="42" fill="none" stroke="var(--helm-dark-ecru)" strokeWidth="9" opacity="0.6" />
          <circle cx="50" cy="50" r="42" fill="none" stroke={tier.text} strokeWidth="9" strokeDasharray={`${dash} ${c - dash}`} strokeDashoffset="0" transform="rotate(-90 50 50)" strokeLinecap="round" />
        </svg>
        <div style={{ position: "absolute", inset: 0, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center" }}>
          <div style={{ fontFamily: "var(--font-sans)", fontWeight: 600, fontSize: 44, lineHeight: "44px", color: "var(--helm-dark-green)" }}>{score}</div>
          <div style={{ fontSize: 11, fontWeight: 700, color: "var(--helm-dark-green)", marginTop: 2 }}>Conversion</div>
        </div>
      </div>
      <div style={{ marginTop: 10, fontFamily: "var(--font-sans)", fontSize: 10, fontWeight: 700, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--helm-dark-grey)", textAlign: "center", maxWidth: 130 }}>{caption}</div>
    </div>
  );
};

const CoverageBar = ({ hero }) => {
  const { min, max, rec, current } = hero;
  const pct = (v) => Math.max(0, Math.min(100, ((v - min) / (max - min)) * 100));
  const recPct = pct(rec);
  // band: gap (current→rec) for policyholder; otherwise a ±13% window around rec
  const bandL = current != null ? pct(current) : Math.max(0, recPct - 13);
  const bandR = current != null ? recPct : Math.min(100, recPct + 13);
  return (
    <div>
      <p style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 13, lineHeight: "18px", color: "var(--helm-dark-grey)", margin: 0, maxWidth: 380 }}>{hero.blurb}</p>
      <div style={{ position: "relative", height: 50, marginTop: 24 }}>
        {/* recommended label + pointer */}
        <div style={{ position: "absolute", left: `${recPct}%`, bottom: 18, transform: "translateX(-50%)", background: "var(--helm-dark-orange)", color: "var(--helm-white)", fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14, padding: "5px 11px", borderRadius: 9, whiteSpace: "nowrap" }}>{CP_money(rec)}</div>
        <div style={{ position: "absolute", left: `${recPct}%`, bottom: 9, transform: "translateX(-50%)", width: 0, height: 0, borderLeft: "6px solid transparent", borderRight: "6px solid transparent", borderTop: "9px solid var(--helm-dark-orange)" }} />
        {/* track */}
        <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 9, borderRadius: 5, background: "var(--helm-dark-ecru)" }} />
        {/* band */}
        <div style={{ position: "absolute", left: `${bandL}%`, width: `${bandR - bandL}%`, bottom: 0, height: 9, borderRadius: 5, background: "var(--helm-orange)" }} />
        {/* current marker (gap leads) */}
        {current != null && (
          <div style={{ position: "absolute", left: `${pct(current)}%`, bottom: -4, transform: "translateX(-50%)", width: 3, height: 17, borderRadius: 2, background: "var(--helm-dark-green)" }} />
        )}
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", marginTop: 10, fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 12, color: "var(--helm-dark-grey)" }}>
        <span>{CP_money(min)}</span>
        {current != null && <span style={{ color: "var(--helm-dark-green)" }}>Now {CP_money(current)}</span>}
        <span>{CP_money(max)}</span>
      </div>
    </div>
  );
};

const Kv = ({ k, v }) => (
  <div>
    <div style={{ fontSize: 12, color: "var(--helm-dark-grey)" }}>{k}</div>
    <div style={{ fontSize: 15, fontWeight: 700, color: "var(--helm-dark-green)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{v}</div>
  </div>
);

const SignalRow = ({ s }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 12px 8px 16px", borderRadius: 19, border: "1px solid var(--helm-dark-ecru)", minHeight: 38 }}>
    {s.dir === "up" && <span style={{ color: "var(--helm-dark-blue)", fontSize: 13, flexShrink: 0 }}>▲</span>}
    {s.dir === "down" && <span style={{ color: "#E20707", fontSize: 13, flexShrink: 0 }}>▼</span>}
    <span style={{ fontWeight: 600, fontSize: 14 }}>{s.text}</span>
    {s.tag && (
      <span style={{ marginLeft: "auto", flexShrink: 0 }}>
        <span className={s.strong ? "chip chip-soft" : "chip chip-outline"} style={{ fontSize: 12 }}>
          {s.strong && <span style={{ color: "var(--helm-chartreuse-2)" }}>◎</span>}{s.tag}
        </span>
      </span>
    )}
  </div>
);

const ActIcon = ({ name }) => {
  const common = { width: 22, height: 22, viewBox: "0 0 24 24", fill: "var(--helm-dark-green)" };
  if (name === "bank") return <svg {...common}><path d="M4 10h2v7H4zm5 0h2v7H9zm9 0h-2v7h2zm-4 0h-2v7h2zM2 22h20v-2H2v2zM12 1L2 6v2h20V6L12 1z" /></svg>;
  if (name === "mail") return <svg {...common}><path d="M22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6zm-2 0l-8 5-8-5h16zm0 12H4V8l8 5 8-5v10z" /></svg>;
  if (name === "ai") return <span className="helm-star" style={{ width: 20, height: 20, color: "var(--helm-dark-green)", display: "inline-block" }} />;
  return <svg {...common}><path d="M15.5 14h-.79l-.28-.27A6.5 6.5 0 1 0 13 15.5l.27.28v.79l5 5 1.5-1.5-5-5zM9.5 14A4.5 4.5 0 1 1 14 9.5 4.51 4.51 0 0 1 9.5 14z" /></svg>;
};

const ActivityFeed = ({ activity }) => (
  <div>
    {activity.map((a, i) => (
      <div key={i} style={{ borderTop: i === 0 ? "none" : "1px solid var(--helm-dark-ecru)" }}>
        <div style={{ display: "flex", gap: 12, alignItems: "center", padding: "10px 0" }}>
          <div style={{ width: 28, height: 28, flexShrink: 0, display: "grid", placeItems: "center" }}><ActIcon name={a.icon} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: "var(--font-sans)", fontWeight: 700, fontSize: 14, lineHeight: "18px", color: "var(--helm-dark-green)" }}>{a.title}</div>
            <div style={{ fontFamily: "var(--font-sans)", fontSize: 12, color: "var(--helm-dark-grey)", marginTop: 3 }}>{a.date}</div>
          </div>
        </div>
      </div>
    ))}
  </div>
);

const ringCaption = (lead, detail) =>
  lead.type === "bene_post" ? (lead.engaged === false ? "Re-engage" : "Conversion ready") : (detail.phase ? detail.phase.label : "Lead");

const DetailMiddle = ({ lead, detail }) => (
  <div style={{ flex: 1, minWidth: 0, padding: "28px 36px", display: "flex", flexDirection: "column", gap: 14 }}>
    <InfoCard>
      <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
        <ScoreRing score={lead.score} caption={ringCaption(lead, detail)} />
        <div style={{ width: 1, alignSelf: "stretch", minHeight: 124, background: "var(--helm-dark-ecru)" }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <CardTitle accent="var(--helm-orange)">{detail.hero.label}</CardTitle>
          <CoverageBar hero={detail.hero} />
        </div>
      </div>
    </InfoCard>

    <InfoCard>
      <CardTitle accent="var(--helm-chartreuse-2)">Key data</CardTitle>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: "18px 16px" }}>
        {detail.keyData.map(([k, v]) => <Kv key={k} k={k} v={v} />)}
      </div>
    </InfoCard>

    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, alignItems: "start" }}>
      <InfoCard>
        <CardTitle accent="var(--helm-dark-blue)">Signals</CardTitle>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {detail.signals.map((s, i) => <SignalRow key={i} s={s} />)}
        </div>
      </InfoCard>
      <InfoCard style={{ paddingBottom: 12 }}>
        <CardTitle accent="var(--helm-dark-purple)">Activity</CardTitle>
        <ActivityFeed activity={detail.activity} />
      </InfoCard>
    </div>
  </div>
);

// ----------------------------------------------------------------- page
const LeadDetail = ({ lead, dim = false, onBack, onGenerateCampaign, children }) => {
  const detail = CP_buildDetail(lead);
  return (
    <div className="marc-page" style={{ display: "flex", flexDirection: "column" }}>
      <DetailNav onBack={onBack} />
      <div style={{ flex: 1, minHeight: 0, overflowY: "auto" }}>
        <div style={{ display: "flex", alignItems: "stretch", minHeight: "100%" }}>
          <DetailLeftRail lead={lead} detail={detail} onGenerateCampaign={onGenerateCampaign} />
          <DetailMiddle lead={lead} detail={detail} />
        </div>
      </div>
      {dim && <div className="scrim" />}
      {children}
    </div>
  );
};

Object.assign(window, { LeadDetail });
