// Candidate detail with score breakdown + call prep — the hero screen

const { StatusPill, RecPill, Avatar, ScoreRing, ScoreBar, FairnessBanner, scoreColor, REC_STYLES } = window.UI;
const { WEIGHT_LABELS } = window.SCREENS_A;

// Mask sensitive PII (PDPA): email/phone hidden until reviewer reveals.
// In production, the reveal would write an audit-log entry server-side.
const maskEmail = (e) => {
  if (!e) return "";
  const [user, domain] = e.split("@");
  if (!domain) return e;
  const visible = user.slice(0, 2);
  return `${visible}${"•".repeat(Math.max(3, user.length - 2))}@${domain}`;
};
const maskPhone = (p) => {
  if (!p) return "";
  const last = p.replace(/[^\d]/g, "").slice(-2);
  return p.slice(0, 4) + " ••• ••" + last;
};
const MaskedField = ({ icon, value, type }) => {
  const [revealed, setRevealed] = React.useState(false);
  const display = revealed
    ? value
    : (type === "email" ? maskEmail(value) : type === "phone" ? maskPhone(value) : value);
  return (
    <span className="row gap-6 muted" style={{ alignItems: "center" }}>
      <Icon name={icon} size={12}/>
      <span style={{ fontVariantNumeric: "tabular-nums" }}>{display}</span>
      <button
        type="button"
        onClick={() => setRevealed(r => !r)}
        title={revealed ? "Hide (logged in audit)" : "Reveal (logged in audit)"}
        style={{
          border: "none", background: "transparent", cursor: "pointer",
          color: "var(--text-subtle)", padding: 0, marginLeft: 2,
          fontSize: 11, textDecoration: "underline",
        }}
      >
        {revealed ? "hide" : "reveal"}
      </button>
    </span>
  );
};

// Generate sensible fallback content for candidates that don't have rich payloads
const fillCandidate = (c, position) => {
  if (c.strengths) return c; // already rich
  const rec = c.recommendation || "Potential fit";
  const weak = rec === "Weak fit" || rec === "Not recommended";
  const partialList = (position?.mustHave || []).slice(0, 2).map(r => ({ req: r, cand: weak ? "Not clearly evidenced in resume" : "Likely match — verify on call", status: weak ? "miss" : "partial" }));
  return {
    ...c,
    strengths: c.strengths || [
      `${c.yearsExperience} years of experience in ${position?.department || "the field"}.`,
      `Currently at ${c.currentCompany} as ${c.currentTitle}.`,
      ...(c.subscores?.industry >= 80 ? ["Strong industry-fit signal from past employers."] : []),
      ...(c.subscores?.stability >= 80 ? ["Stable tenure pattern across recent roles."] : []),
    ],
    weaknesses: c.weaknesses || [
      ...(c.subscores?.leadership < 60 ? ["Limited leadership / team-management signal."] : []),
      ...(c.subscores?.skills < 70 ? ["Some required skills not explicitly listed."] : []),
      "Several KPI metrics not quantified in resume — verify on call.",
    ].slice(0, 3),
    risks: c.risks || [
      ...(c.subscores?.stability < 60 ? ["Short average tenure — possible job-hopping risk."] : []),
      ...(c.riskFlags > 0 ? [`${c.riskFlags} ${c.riskFlags === 1 ? "flag" : "flags"} raised by the model — review carefully.`] : []),
      ...(weak ? ["Multiple must-have requirements not evidenced in the resume."] : ["No critical risks identified."]),
    ],
    missing: c.missing || [],
    interviewQuestions: c.interviewQuestions || [
      `Walk me through a transaction or project from your time at ${c.currentCompany} that you're most proud of.`,
      `Why are you considering a move? What's not working in your current role?`,
      `What's your view on the Bangkok ${position?.department?.toLowerCase() || "real estate"} market over the next 12 months?`,
      `Describe a deal or initiative that didn't go well, and what you learned.`,
      `What does success look like for you in the first 90 days here?`,
    ],
    kpiAlignment: c.kpiAlignment || (position?.kpis || []).map(k => ({
      kpi: k, status: weak ? "miss" : "partial",
      note: weak ? "No supporting evidence in resume." : "Likely match — confirm on call with specific numbers."
    })),
    requirementMatch: c.requirementMatch || [
      ...(position?.mustHave || []).map((r, i) => ({ req: r, cand: weak ? "Not evidenced" : (i === 0 ? `${c.yearsExperience} yrs at ${c.currentCompany}` : "Verify on call"), status: weak ? "miss" : (i === 0 ? "match" : "partial") })),
      ...partialList,
    ],
    workHistory: c.workHistory || [
      { company: c.currentCompany, title: c.currentTitle, years: "Current", duration: `${Math.min(c.yearsExperience, 4)} yrs`, note: "Most recent role" },
      ...(c.yearsExperience > 4 ? [{ company: "Previous employer", title: "Earlier role", years: `~${c.yearsExperience - 3} yrs prior`, duration: `${c.yearsExperience - 3} yrs`, note: "Detailed history available in resume PDF" }] : []),
    ],
    education: c.education || [{ school: "Details available in resume", degree: "Bachelor's degree", years: "—" }],
    certs: c.certs || [],
    callPrep: c.callPrep || {
      summary: `${c.yearsExperience}-year ${c.currentTitle.toLowerCase()} from ${c.currentCompany}. ${rec === "Strong fit" ? "Strong on the dimensions that matter most for this role." : rec === "Potential fit" ? "Promising profile with several gaps to clarify on the call." : "Several material gaps — call only if shortlist is thin."} Verify the specifics that aren't quantified in the resume.`,
      verify: ["Personal vs team-attributed results", "Reasons for considering a move", "Salary expectation flexibility"],
      salary: [`Confirm THB expectation against role band.`, "Comfort with commission-heavy structures."],
      availability: [`Notice period: ${c.noticePeriod}.`, "Earliest realistic start date."],
      concerns: weak ? ["Several must-haves not evidenced — confirm in detail."] : ["Quantify KPI claims with concrete numbers."],
      nextStep: rec === "Strong fit" ? "Recommend 60-min interview with hiring manager." : rec === "Potential fit" ? "Hold pending verification call results." : "Likely move to talent pool unless verification surfaces new evidence.",
    },
  };
};

const CandidateDetail = ({ candidate: rawCandidate, position, candidates, onBack, onOpen, scoreVizMode = "both", showFairness = true, aiTone = "cautious", canEdit = false }) => {
  const candidate = React.useMemo(() => fillCandidate(rawCandidate, position), [rawCandidate, position]);
  const [tab, setTab] = React.useState("score");
  const [override, setOverride] = React.useState(null);
  const [overrideReason, setOverrideReason] = React.useState("");
  const [statusBusy, setStatusBusy] = React.useState("");
  const [noteDraft, setNoteDraft] = React.useState("");
  const [savingNote, setSavingNote] = React.useState(false);
  const { t } = window.I18N.useI18n();

  const changeStatus = async (newStatus) => {
    if (!canEdit || !window.DATA?.api?.updateCandidateStatus) return;
    setStatusBusy("กำลังบันทึก " + newStatus + "…");
    const { error } = await window.DATA.api.updateCandidateStatus(candidate.id, newStatus);
    setStatusBusy(error ? "❌ บันทึกไม่สำเร็จ: " + error.message : "✓ บันทึกเป็น " + newStatus + " แล้ว");
    setTimeout(() => setStatusBusy(""), 2200);
  };

  const saveOverride = async () => {
    if (!canEdit || override == null || !window.DATA?.api?.saveCandidate) return;
    setStatusBusy("กำลังบันทึก override…");
    const updated = { ...candidate, score: override, scoreOverride: { value: override, reason: overrideReason, by: "current_user", at: new Date().toISOString() } };
    const { error } = await window.DATA.api.saveCandidate(updated);
    setStatusBusy(error ? "❌ " + error.message : "✓ บันทึก score override แล้ว");
    if (!error) setOverride(null);
    setTimeout(() => setStatusBusy(""), 2200);
  };

  // Sibling navigation
  const siblings = candidates.filter(c => c.positionId === candidate.positionId).sort((a, b) => b.score - a.score);
  const idx = siblings.findIndex(c => c.id === candidate.id);
  const prev = idx > 0 ? siblings[idx - 1] : null;
  const next = idx < siblings.length - 1 ? siblings[idx + 1] : null;

  return (
    <div className="fade-in">
      {/* Sub-nav: prev/next + back */}
      <div className="row mb-12" style={{ justifyContent: "space-between" }}>
        <button className="btn btn-quiet btn-sm" onClick={onBack}>
          <Icon name="arrow-right" size={12} style={{ transform: "rotate(180deg)" }}/>
          {t.cand.backTo} {position.title}
        </button>
        <div className="row gap-4">
          <span className="muted" style={{ fontSize: 12, marginRight: 8 }}>
            {t.cand.rankedOf(idx + 1, siblings.length)}
          </span>
          <button className="icon-btn" disabled={!prev} onClick={() => prev && onOpen("candidate", prev.id)} style={{ opacity: prev ? 1 : 0.4 }}>
            <Icon name="arrow-right" size={14} style={{ transform: "rotate(180deg)" }}/>
          </button>
          <button className="icon-btn" disabled={!next} onClick={() => next && onOpen("candidate", next.id)} style={{ opacity: next ? 1 : 0.4 }}>
            <Icon name="arrow-right" size={14}/>
          </button>
        </div>
      </div>

      {/* Header card */}
      <div className="card card-pad mb-16">
        <div className="row gap-16" style={{ alignItems: "flex-start" }}>
          <Avatar initials={candidate.initials} color={candidate.avatarColor} size="lg"/>
          <div className="flex-1">
            <div className="row gap-12" style={{ alignItems: "baseline" }}>
              <h1 style={{ fontFamily: "var(--font-serif)", fontSize: 26, fontWeight: 500, margin: 0, color: "var(--green-900)", letterSpacing: "-0.01em" }}>
                {candidate.name}
              </h1>
              <StatusPill status={candidate.status}/>
            </div>
            <div className="row gap-12 mt-4 muted" style={{ fontSize: 13.5 }}>
              <span>{candidate.currentTitle} · {candidate.currentCompany}</span>
              <span>·</span>
              <span>{candidate.yearsExperience} {t.yrs}</span>
            </div>
            <div className="row gap-16 mt-12" style={{ flexWrap: "wrap", fontSize: 12.5 }}>
              <MaskedField icon="mail" value={candidate.email} type="email"/>
              <MaskedField icon="phone" value={candidate.phone} type="phone"/>
              <span className="row gap-6 muted"><Icon name="map-pin" size={12}/>{candidate.location}</span>
              <span className="row gap-6 muted"><Icon name="calendar" size={12}/>{t.cand.applied} {candidate.appliedDate}</span>
              <span className="row gap-6 muted"><Icon name="external" size={12}/>{t.cand.source}: {candidate.source}</span>
            </div>
          </div>
          <div className="col gap-8" style={{ alignItems: "flex-end" }}>
            <div className="row gap-8">
              <button className="btn btn-ghost" onClick={async () => {
                if (candidate.resumePath && window.DATA?.api?.getResumeUrl) {
                  const url = await window.DATA.api.getResumeUrl(candidate.resumePath);
                  if (url) window.open(url, "_blank");
                  else setStatusBusy("❌ ไม่พบไฟล์เรซูเม่");
                } else {
                  setStatusBusy("ℹ️ candidate นี้ยังไม่มี resume ที่ upload");
                }
                setTimeout(() => setStatusBusy(""), 2500);
              }}><Icon name="file-text" size={14}/>{t.cand.viewResume}</button>
              <button className="btn btn-ghost"><Icon name="more" size={14}/></button>
              <button className="btn btn-primary"><Icon name="phone" size={14}/>{t.cand.scheduleCall}</button>
            </div>
            <div className="muted" style={{ fontSize: 12 }}>
              {t.cand.evaluating} <b style={{ color: "var(--text)" }}>{position.title}</b>
            </div>
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="tabs">
        {[
          { id: "score", label: t.cand.tabs.score },
          { id: "compare", label: t.cand.tabs.compare },
          { id: "callprep", label: t.cand.tabs.call },
          { id: "resume", label: t.cand.tabs.resume },
        ].map(tt => (
          <button key={tt.id} className={"tab " + (tab === tt.id ? "active" : "")} onClick={() => setTab(tt.id)}>{tt.label}</button>
        ))}
      </div>

      {tab === "score" && <ScoreTab candidate={candidate} position={position} scoreVizMode={scoreVizMode} showFairness={showFairness} aiTone={aiTone} override={override} setOverride={setOverride}/>}
      {tab === "compare" && <CompareTab candidate={candidate} position={position}/>}
      {tab === "callprep" && <CallPrepTab candidate={candidate} aiTone={aiTone}/>}
      {tab === "resume" && <ResumeTab candidate={candidate}/>}
    </div>
  );
};

const ScoreTab = ({ candidate, position, scoreVizMode, showFairness, aiTone, override, setOverride }) => {
  const recStyle = REC_STYLES[candidate.recommendation] || {};
  const { t } = window.I18N.useI18n();
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18 }}>
      <div className="col gap-12">
        {showFairness && <FairnessBanner show={true}/>}

        {/* Big score card */}
        <div className="card card-pad">
          <div className="row gap-24" style={{ alignItems: "center" }}>
            {(scoreVizMode === "ring" || scoreVizMode === "both") && <ScoreRing score={candidate.score} size={120}/>}
            <div className="flex-1 col gap-8">
              <div className="page-eyebrow">{t.cand.overall}</div>
              <div className="row gap-8" style={{ alignItems: "baseline" }}>
                <span style={{ fontFamily: "var(--font-serif)", fontSize: 44, fontWeight: 500, lineHeight: 1, color: "var(--green-900)", letterSpacing: "-0.02em" }}>
                  {override ?? candidate.score}
                </span>
                <span className="muted">/ 100</span>
                <RecPill rec={candidate.recommendation}/>
              </div>
              <div className="muted mt-4" style={{ fontSize: 13.5, lineHeight: 1.55, maxWidth: "60ch" }}>
                {t.cand.explanations[aiTone] || t.cand.explanations.cautious}
              </div>
            </div>
          </div>
        </div>

        {/* Sub-scores */}
        {(scoreVizMode === "bars" || scoreVizMode === "both") && (
          <div className="card card-pad">
            <div className="row mb-16" style={{ justifyContent: "space-between" }}>
              <div className="card-title">{t.cand.subscores}</div>
              <span className="muted" style={{ fontSize: 12 }}>{t.cand.subWeighted}</span>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px 28px" }}>
              {Object.entries(candidate.subscores).map(([key, val]) => (
                <ScoreBar key={key} value={val} label={t.weightLabels[key]} weight={position.weights[key]}/>
              ))}
            </div>
          </div>
        )}

        {/* Strengths */}
        <div className="card card-pad">
          <div className="row gap-8 mb-12">
            <Icon name="thumbs-up" size={16} style={{ color: "var(--green-600)" }}/>
            <div className="card-title" style={{ margin: 0 }}>{t.cand.working}</div>
          </div>
          <div className="col gap-10">
            {candidate.strengths.map((s, i) => (
              <div key={i} className="row gap-10" style={{ alignItems: "flex-start" }}>
                <div style={{ width: 6, height: 6, borderRadius: 999, background: "var(--green-500)", marginTop: 8, flexShrink: 0 }}/>
                <span style={{ fontSize: 13.5, lineHeight: 1.55 }}>{s}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Weaknesses + Risks */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <div className="card card-pad">
            <div className="row gap-8 mb-12">
              <Icon name="thumbs-down" size={16} style={{ color: "var(--amber-500)" }}/>
              <div className="card-title" style={{ margin: 0 }}>{t.cand.gaps}</div>
            </div>
            <div className="col gap-10">
              {candidate.weaknesses.map((s, i) => (
                <div key={i} className="row gap-10" style={{ alignItems: "flex-start" }}>
                  <div style={{ width: 6, height: 6, borderRadius: 999, background: "var(--amber-500)", marginTop: 8, flexShrink: 0 }}/>
                  <span style={{ fontSize: 13.5, lineHeight: 1.55 }}>{s}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="card card-pad">
            <div className="row gap-8 mb-12">
              <Icon name="flag" size={16} style={{ color: "var(--rose-500)" }}/>
              <div className="card-title" style={{ margin: 0 }}>{t.cand.risks}</div>
            </div>
            <div className="col gap-10">
              {candidate.risks.map((s, i) => (
                <div key={i} className="row gap-10" style={{ alignItems: "flex-start" }}>
                  <div style={{ width: 6, height: 6, borderRadius: 999, background: "var(--rose-500)", marginTop: 8, flexShrink: 0 }}/>
                  <span style={{ fontSize: 13.5, lineHeight: 1.55 }}>{s}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Right rail */}
      <div className="col gap-12">
        <div className="card card-pad">
          <div className="card-title mb-12">{t.cand.override}</div>
          <div className="muted mb-16" style={{ fontSize: 13, lineHeight: 1.55 }}>
            {t.cand.overrideSub}
          </div>
          <div className="col gap-12">
            <div className="col gap-6">
              <span className="field-label">{t.cand.yourScore}</span>
              <div className="row gap-8">
                <input type="number" min="0" max="100" className="field-input" placeholder={candidate.score} style={{ width: 90 }} value={override ?? ""} onChange={e => setOverride(e.target.value === "" ? null : Math.max(0, Math.min(100, +e.target.value)))}/>
                {override != null && <button className="btn btn-quiet btn-sm" onClick={() => setOverride(null)}>{t.cand.resetBtn}</button>}
              </div>
            </div>
            <div className="col gap-6">
              <span className="field-label">{t.cand.reason}</span>
              <textarea className="field-input" placeholder={t.cand.reasonPh} value={overrideReason} onChange={e => setOverrideReason(e.target.value)} disabled={!canEdit}/>
            </div>
            <button className="btn btn-primary" disabled={override == null || !canEdit} onClick={saveOverride} style={(override == null || !canEdit) ? { opacity: 0.5 } : {}}>{t.cand.saveOverride}</button>
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-title mb-12">{t.cand.quick}</div>
          <div className="col gap-8">
            <ActionRow icon="phone"    label={t.cand.actions.phone[0]} sub={t.cand.actions.phone[1]} onClick={canEdit && (() => changeStatus("Call scheduled"))}     disabled={!canEdit}/>
            <ActionRow icon="star"     label={t.cand.actions.star[0]}  sub={t.cand.actions.star[1]}  onClick={canEdit && (() => changeStatus("Shortlisted"))}        disabled={!canEdit}/>
            <ActionRow icon="calendar" label={t.cand.actions.cal[0]}   sub={t.cand.actions.cal[1]}   onClick={canEdit && (() => changeStatus("Interview scheduled"))} disabled={!canEdit}/>
            <ActionRow icon="users"    label={t.cand.actions.users[0]} sub={t.cand.actions.users[1]} onClick={canEdit && (() => changeStatus("Interviewed"))}         disabled={!canEdit}/>
            <ActionRow icon="x"        label={t.cand.actions.x[0]}     sub={t.cand.actions.x[1]}     onClick={canEdit && (() => changeStatus("Rejected"))} danger    disabled={!canEdit}/>
          </div>
          {statusBusy && <div className="muted mt-8" style={{ fontSize: 12 }}>{statusBusy}</div>}
        </div>

        <div className="card card-pad">
          <div className="row mb-8" style={{ justifyContent: "space-between" }}>
            <div className="card-title" style={{ margin: 0 }}>{t.cand.record}</div>
            <span className="pill pill-outline">v3</span>
          </div>
          <div className="col gap-8" style={{ fontSize: 12.5 }}>
            <RecordRow k={t.cand.records.evaluated} v="Apr 28, 2026 · 09:14"/>
            <RecordRow k={t.cand.records.model} v="Claude Sonnet 4.5"/>
            <RecordRow k={t.cand.records.jd} v="pos_001 · v2"/>
            <RecordRow k={t.cand.records.resume} v="cand_001 · v1"/>
            <RecordRow k={t.cand.records.reviewer} v="—"/>
          </div>
          <div className="divider"/>
          <button className="btn btn-quiet btn-sm" style={{ width: "100%" }}>
            <Icon name="history" size={12}/>{t.cand.audit}
          </button>
        </div>
      </div>
    </div>
  );
};

const ActionRow = ({ icon, label, sub, danger, onClick, disabled }) => (
  <button onClick={onClick || undefined} disabled={disabled} className="row gap-10" style={{
    width: "100%", padding: "10px 12px", border: "1px solid var(--border)",
    borderRadius: 8, background: "#fff",
    cursor: disabled ? "not-allowed" : "pointer", textAlign: "left",
    opacity: disabled ? 0.5 : 1,
  }}>
    <div style={{
      width: 28, height: 28, borderRadius: 8,
      background: danger ? "var(--rose-100)" : "var(--green-100)",
      color: danger ? "var(--rose-600)" : "var(--green-700)",
      display: "grid", placeItems: "center"
    }}><Icon name={icon} size={14}/></div>
    <div className="col flex-1">
      <span style={{ fontSize: 13, fontWeight: 500, color: danger ? "var(--rose-700)" : "var(--text)" }}>{label}</span>
      <span className="subtle" style={{ fontSize: 11.5 }}>{sub}</span>
    </div>
    <Icon name="chevron-right" size={12} style={{ color: "var(--text-subtle)" }}/>
  </button>
);

const RecordRow = ({ k, v }) => (
  <div className="row" style={{ justifyContent: "space-between" }}>
    <span className="muted">{k}</span>
    <span style={{ fontWeight: 500 }}>{v}</span>
  </div>
);

const CompareTab = ({ candidate, position }) => {
  const { t } = window.I18N.useI18n();
  return (
  <div className="col gap-16">
    <div className="card">
      <div className="card-head">
        <div>
          <div className="card-title">{t.cand.reqsTitle}</div>
          <div className="card-sub">{t.cand.reqsSub}</div>
        </div>
        <div className="row gap-12">
          <Legend color="var(--green-100)" iconColor="var(--green-700)" icon="check" label={t.cand.legend.match}/>
          <Legend color="var(--amber-100)" iconColor="var(--amber-600)" icon="alert" label={t.cand.legend.partial}/>
          <Legend color="var(--rose-100)" iconColor="var(--rose-600)" icon="x" label={t.cand.legend.miss}/>
        </div>
      </div>
      <div style={{ padding: "0 22px" }}>
        <div className="compare-row" style={{ paddingTop: 14 }}>
          <div className="compare-cell req field-label" style={{ marginBottom: 0 }}>{t.cand.reqHead}</div>
          <div></div>
          <div className="compare-cell cand field-label" style={{ marginBottom: 0 }}>{t.cand.foundHead}</div>
        </div>
        {candidate.requirementMatch.map((r, i) => (
          <div key={i} className="compare-row">
            <div className="compare-cell req">{r.req}</div>
            <div className={"compare-status " + r.status}>
              {r.status === "match" ? "✓" : r.status === "partial" ? "◐" : "✗"}
            </div>
            <div className="compare-cell cand">{r.cand}</div>
          </div>
        ))}
      </div>
    </div>

    <div className="card">
      <div className="card-head">
        <div className="card-title">{t.cand.kpiTitle}</div>
        <div className="card-sub">{t.cand.kpiSub}</div>
      </div>
      <div style={{ padding: "0 22px 16px" }}>
        {candidate.kpiAlignment.map((k, i) => (
          <div key={i} className="row gap-12" style={{ padding: "14px 0", borderBottom: i < candidate.kpiAlignment.length - 1 ? "1px solid var(--border)" : "none", alignItems: "flex-start" }}>
            <div className={"compare-status " + k.status} style={{ marginTop: 1 }}>
              {k.status === "match" ? "✓" : k.status === "partial" ? "◐" : "✗"}
            </div>
            <div className="col flex-1 gap-4">
              <span style={{ fontSize: 13.5, fontWeight: 500 }}>{k.kpi}</span>
              <span className="muted" style={{ fontSize: 12.5, lineHeight: 1.5 }}>{k.note}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  </div>
  );
};

const Legend = ({ color, iconColor, icon, label }) => (
  <span className="row gap-6" style={{ fontSize: 12 }}>
    <span style={{ width: 18, height: 18, borderRadius: 999, background: color, color: iconColor, display: "grid", placeItems: "center" }}>
      <Icon name={icon} size={10}/>
    </span>
    <span className="muted">{label}</span>
  </span>
);

const CallPrepTab = ({ candidate, aiTone }) => {
  const cp = candidate.callPrep;
  const { t } = window.I18N.useI18n();
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
      <div className="col gap-12">
        <div className="card card-pad">
          <div className="row gap-8 mb-12">
            <Icon name="sparkles" size={16} style={{ color: "var(--green-600)" }}/>
            <div className="card-title" style={{ margin: 0 }}>{t.cand.callSummary}</div>
          </div>
          <p style={{ margin: 0, lineHeight: 1.65, fontSize: 14 }}>{cp.summary}</p>
        </div>

        <div className="card card-pad">
          <div className="card-title mb-12">{t.cand.suggestedQs}</div>
          <ol style={{ margin: 0, paddingLeft: 22, lineHeight: 1.7 }}>
            {candidate.interviewQuestions.map((q, i) => (
              <li key={i} style={{ paddingLeft: 4, marginBottom: 10, fontSize: 13.5 }}>{q}</li>
            ))}
          </ol>
          <div className="row gap-8 mt-16">
            <button className="btn btn-ghost btn-sm" onClick={() => setStatusBusy("ℹ️ Regenerate ต้องเชื่อม AI API — ยังไม่พร้อม")} onMouseLeave={() => statusBusy.startsWith("ℹ️") && setTimeout(() => setStatusBusy(""), 1)}><Icon name="sparkles" size={12}/>{t.cand.regenerate}</button>
            <button className="btn btn-ghost btn-sm" onClick={async () => {
              const text = candidate.interviewQuestions.map((q, i) => `${i + 1}. ${q}`).join("\n");
              try {
                await navigator.clipboard.writeText(text);
                setStatusBusy("✓ คัดลอกคำถามไปยัง clipboard แล้ว");
              } catch {
                setStatusBusy("❌ คัดลอกไม่สำเร็จ — เบราว์เซอร์ปฏิเสธ");
              }
              setTimeout(() => setStatusBusy(""), 2200);
            }}><Icon name="download" size={12}/>{t.cand.copy}</button>
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-title mb-12">{t.cand.verifyTitle}</div>
          <div className="col gap-10">
            {cp.verify.map((v, i) => (
              <div key={i} className="row gap-10">
                <Icon name="alert" size={14} style={{ color: "var(--amber-500)", marginTop: 2, flexShrink: 0 }}/>
                <span style={{ fontSize: 13.5 }}>{v}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="card card-pad">
          <div className="card-title mb-12">{t.cand.notes}</div>
          <textarea
            className="field-input"
            placeholder={t.cand.notesPh}
            style={{ minHeight: 120 }}
            value={noteDraft}
            onChange={(e) => setNoteDraft(e.target.value)}
            disabled={!canEdit}
          />
          <div className="row gap-8 mt-12">
            <button
              className="btn btn-primary btn-sm"
              disabled={!canEdit || !noteDraft.trim() || savingNote}
              onClick={async () => {
                if (!canEdit || !window.DATA?.api?.saveCandidate) return;
                setSavingNote(true);
                const newNote = { ts: new Date().toISOString(), by: "current_user", text: noteDraft.trim() };
                const updated = { ...candidate, notes: [...(candidate.notes || []), newNote] };
                const { error } = await window.DATA.api.saveCandidate(updated);
                setSavingNote(false);
                if (error) { setStatusBusy("❌ " + error.message); }
                else { setNoteDraft(""); setStatusBusy("✓ บันทึก note แล้ว"); }
                setTimeout(() => setStatusBusy(""), 2200);
              }}
            >{savingNote ? "กำลังบันทึก…" : t.cand.saveNote}</button>
            <button
              className="btn btn-ghost btn-sm"
              onClick={() => setNoteDraft(d => d + (d ? "\n" : "") + "[" + new Date().toLocaleString() + "] ")}
              disabled={!canEdit}
            >{t.cand.addTs}</button>
          </div>
          {(candidate.notes || []).length > 0 && (
            <div className="col gap-8 mt-16">
              <div className="muted" style={{ fontSize: 11.5, textTransform: "uppercase", letterSpacing: 0.06 }}>Previous notes</div>
              {[...candidate.notes].reverse().map((n, i) => (
                <div key={i} className="muted" style={{ fontSize: 12.5, padding: 8, background: "var(--sand-50)", borderRadius: 6 }}>
                  <div style={{ fontSize: 11, color: "var(--text-muted)" }}>{new Date(n.ts).toLocaleString()}</div>
                  <div style={{ whiteSpace: "pre-wrap", marginTop: 2 }}>{n.text}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="col gap-12">
        <CallSection title={t.cand.salary} icon="info" items={cp.salary}/>
        <CallSection title={t.cand.availability} icon="calendar" items={cp.availability}/>
        <CallSection title={t.cand.concerns} icon="flag" items={cp.concerns} accent="rose"/>

        <div className="card card-pad" style={{ background: "var(--green-50)", borderColor: "var(--green-100)" }}>
          <div className="row gap-8 mb-8">
            <Icon name="arrow-right" size={16} style={{ color: "var(--green-700)" }}/>
            <div className="card-title" style={{ margin: 0, color: "var(--green-900)" }}>{t.cand.nextStep}</div>
          </div>
          <p style={{ margin: 0, fontSize: 13.5, lineHeight: 1.55, color: "var(--sand-800)" }}>{cp.nextStep}</p>
        </div>
      </div>
    </div>
  );
};

const CallSection = ({ title, icon, items, accent }) => (
  <div className="card card-pad">
    <div className="row gap-8 mb-12">
      <Icon name={icon} size={15} style={{ color: accent === "rose" ? "var(--rose-500)" : "var(--green-600)" }}/>
      <div className="card-title" style={{ margin: 0 }}>{title}</div>
    </div>
    <ul style={{ margin: 0, paddingLeft: 18, lineHeight: 1.65 }}>
      {items.map((it, i) => <li key={i} style={{ marginBottom: 6, fontSize: 13.5 }}>{it}</li>)}
    </ul>
  </div>
);

const ResumeTab = ({ candidate }) => {
  const { t } = window.I18N.useI18n();
  return (
  <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 18 }}>
    <div className="col gap-12">
      <div className="card card-pad">
        <div className="card-title mb-16">{t.cand.workHist}</div>
        <div className="col gap-16">
          {candidate.workHistory.map((w, i) => (
            <div key={i} className="row gap-12" style={{ alignItems: "flex-start" }}>
              <div style={{
                width: 36, height: 36, borderRadius: 8,
                background: "var(--sand-200)", color: "var(--sand-800)",
                display: "grid", placeItems: "center", fontSize: 14, fontWeight: 600, flexShrink: 0,
                fontFamily: "var(--font-serif)"
              }}>{w.company[0]}</div>
              <div className="col flex-1 gap-4">
                <div className="row" style={{ justifyContent: "space-between" }}>
                  <div style={{ fontWeight: 500, fontSize: 14 }}>{w.title}</div>
                  <span className="muted" style={{ fontSize: 12.5 }}>{w.years}</span>
                </div>
                <div className="row gap-8 muted" style={{ fontSize: 12.5 }}>
                  <span>{w.company}</span>
                  <span>·</span>
                  <span>{w.duration}</span>
                </div>
                {w.note && <div className="muted mt-4" style={{ fontSize: 12.5 }}>{w.note}</div>}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div className="card card-pad">
        <div className="card-title mb-12">{t.cand.educationT}</div>
        {candidate.education.map((e, i) => (
          <div key={i} className="row gap-12" style={{ alignItems: "flex-start", padding: "8px 0" }}>
            <Icon name="star" size={16} style={{ color: "var(--green-600)", marginTop: 2 }}/>
            <div className="col flex-1">
              <div style={{ fontWeight: 500, fontSize: 14 }}>{e.degree}</div>
              <div className="muted" style={{ fontSize: 12.5 }}>{e.school} · {e.years}</div>
            </div>
          </div>
        ))}
      </div>
    </div>

    <div className="col gap-12">
      <div className="card card-pad">
        <div className="card-title mb-12">{t.cand.compAvail}</div>
        <div className="col gap-10" style={{ fontSize: 13.5 }}>
          <RecordRow k={t.cand.salaryExp} v={candidate.salaryExpectation}/>
          <RecordRow k={t.cand.noticePeriod} v={candidate.noticePeriod}/>
        </div>
      </div>
      <div className="card card-pad">
        <div className="card-title mb-12">{t.cand.certsT}</div>
        <div className="col gap-8">
          {candidate.certs.map((c, i) => (
            <div key={i} className="row gap-8">
              <Icon name="check" size={14} style={{ color: "var(--green-600)" }}/>
              <span style={{ fontSize: 13.5 }}>{c}</span>
            </div>
          ))}
        </div>
      </div>
      <div className="card card-pad">
        <div className="card-title mb-12">{t.cand.resumeFile}</div>
        <div className="row gap-12" style={{ padding: "12px 14px", background: "var(--sand-50)", borderRadius: 8 }}>
          <Icon name="file-text" size={20} style={{ color: "var(--rose-500)" }}/>
          <div className="col flex-1">
            <span style={{ fontSize: 13, fontWeight: 500 }}>{candidate.name.replace(/ /g, "_")}_Resume.pdf</span>
            <span className="subtle" style={{ fontSize: 11.5 }}>298 KB · {candidate.appliedDate}</span>
          </div>
          <button className="icon-btn"><Icon name="download" size={14}/></button>
        </div>
      </div>
    </div>
  </div>
  );
};

window.SCREENS_C = { CandidateDetail };
