// ============================================================
//   LayoutReceipt — "AI handoff receipt" layer on Match shell
//   The bet: users don't need source, they need PROOF the AI
//   did sane work. Every candidate carries a plain-language
//   receipt of what happened and why they're here.
//
//   Tone is tweakable: calm ↔ brutally honest. Source stops
//   being a tab and becomes one fact inside a sentence.
// ============================================================
const { color: RC } = window.FF;

const R_OWNERS = {
  ai:     { label:'AI working',   tint: RC.copilot[50], fg: RC.copilot[800], dot: RC.copilot[500] },
  ready:  { label:'Ready for you',tint: RC.primary[50], fg: RC.primary[800], dot: RC.primary[500] },
  active: { label:'In progress',  tint: RC.inform[50],  fg: RC.inform[700],  dot: RC.inform[500] },
  waiting:{ label:'Waiting',      tint: RC.caution[50], fg: RC.caution[700], dot: RC.caution[500] },
};

function r_owner(c) {
  if (c.stage === 'sourcing') return 'ai';
  if (c.unread || c.justLanded) return 'ready';
  const m = (c.lastMsg || '').toLowerCase();
  if (/awaiting|reminder|screening questions/.test(m)) return 'waiting';
  return 'active';
}

// Build the receipt — the proof, as five structured sections.
function buildReceipt(c) {
  const h = c.id.split('').reduce((a, ch) => a + ch.charCodeAt(0), 0);
  const attempts = (h % 3) + 1;
  const applied = c.source === 'applied';
  const board = ['Indeed', 'their company profile', 'ZipRecruiter', 'a job-board repost'][h % 4];
  const replied = c.unread || c.justLanded || /interested|shift|\$|still|confirmed|copilot|scheduled/i.test(c.lastMsg || '');
  const commute = [8, 14, 22, 35][h % 4];

  const steps = applied
    ? ['Applied', 'Matched', 'Screened', replied && 'Replied', 'Scored'].filter(Boolean)
    : ['Sourced', 'Matched', `Texted ${attempts}×`, replied ? 'Replied' : 'No reply yet', 'Scored'].filter(Boolean);

  // 1 — why here
  const whyHere = `Matches ${c.role} — ${commute} min away, ${commute <= 20 ? 'close commute' : 'longer commute'}.`;

  // 2 — how found (tone-sensitive)
  const howCalm = applied
    ? `Applied via ${board}.`
    : `AI-sourced from a prior résumé, contacted ${attempts}×.`;
  const howBlunt = applied
    ? `Applied on their own — they came to you. We never had to chase them.`
    : `Did NOT apply. FactoryFix found them and texted ${attempts}×.`;

  // 3 — what they replied
  const intent = (c.lastMsg && (c.lastMsg.startsWith('"') || c.lastMsg.startsWith('\u201C'))) ? c.lastMsg : null;
  const repliedText = intent
    ? intent
    : replied ? '"Yes — still interested, what\u2019s the pay?"' : 'No reply yet.';

  // 4 — score / risk
  let risk = 'No flags.';
  if (!replied && !applied) risk = `No reply after ${attempts} attempts — cold.`;
  else if (commute >= 35) risk = 'Long commute — may not stick.';
  else if (!applied) risk = 'Hasn\u2019t formally applied yet.';
  else if (c.score < 4) risk = 'Borderline score — review closely.';

  // 5 — why ready
  const ready = replied || applied;
  const whyReady = ready
    ? (applied
        ? 'Applied and cleared screening — ready for your review.'
        : 'Replied and is interested — ready for a call.')
    : 'Not ready — still cold. The AI is still working them.';

  return { steps, whyHere, howCalm, howBlunt, repliedText, risk, whyReady, ready, score: c.score, applied };
}

function LayoutReceipt({ candidates, selectedId, onSelect, tone = 'calm' }) {
  const list = candidates.filter(c => c.stage === 'engaged' || c.stage === 'new');
  return (
    <React.Fragment>
      <div style={{ padding:'14px 20px 6px' }}>
        <div style={{ fontSize:11, fontWeight:700, letterSpacing:'.08em', textTransform:'uppercase', color: RC.shade[700], marginBottom:3 }}>
          Candidates · with handoff receipts
        </div>
        <div style={{ fontSize:12, color: RC.shade[820], lineHeight:1.45 }}>
          Every row shows what the AI did and why this person is here — in words, not an icon.
        </div>
      </div>
      <div style={{ flex:1, overflow:'auto', borderTop:`1px solid ${RC.tint[80]}` }}>
        {list.map(c => (
          <ReceiptRow key={c.id} c={c} tone={tone}
            selected={c.id === selectedId} onSelect={onSelect}/>
        ))}
      </div>
    </React.Fragment>
  );
}

function ReceiptRow({ c, tone, selected, onSelect }) {
  const O = R_OWNERS[r_owner(c)];
  const r = buildReceipt(c);
  const blunt = tone === 'blunt';
  return (
    <div onClick={() => onSelect?.(c.id)} style={{
      position:'relative', padding:'14px 20px 14px 18px',
      borderBottom:`1px solid ${RC.tint[80]}`, cursor:'pointer',
      background: selected ? RC.highlight[50] + '66' : '#fff',
    }}>
      {selected && <div style={{ position:'absolute', left:0, top:0, bottom:0, width:3, background: RC.highlight[500] }}/>}

      {/* identity */}
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8 }}>
        <h3 style={{ margin:0, fontSize:14, fontWeight:700, color: RC.shade[880] }}>{c.name}</h3>
        <span style={{ display:'inline-flex', alignItems:'center', gap:3, padding:'1px 6px 1px 4px', background: RC.primary[500], color:'#fff', fontSize:11, fontWeight:700, borderRadius:4 }}>
          <span style={{ fontSize:9 }}>★</span>{c.score}
        </span>
        <div style={{ flex:1 }}/>
        <span style={{ display:'inline-flex', alignItems:'center', gap:5, padding:'2px 8px 2px 7px', borderRadius:9999, fontSize:11, fontWeight:700, background: O.tint, color: O.fg }}>
          <span style={{ width:6, height:6, borderRadius:'50%', background: O.dot }}/>
          {O.label}
        </span>
      </div>

      {/* THE RECEIPT — five structured sections */}
      <div style={{
        padding:'12px 13px', borderRadius:8,
        background: RC.tint[20], border:`1px solid ${blunt ? RC.shade[840] : RC.tint[80]}`,
      }}>
        {/* journey trail */}
        <div style={{ display:'flex', alignItems:'center', flexWrap:'wrap', gap:0, marginBottom:11, paddingBottom:10, borderBottom:`1px solid ${RC.tint[80]}` }}>
          {r.steps.map((s, i) => (
            <React.Fragment key={i}>
              {i > 0 && <span style={{ color: RC.shade[500], margin:'0 5px', fontSize:10 }}>→</span>}
              <span style={{
                fontSize:10.5, fontWeight:600, padding:'2px 7px', borderRadius:9999,
                background: s.includes('No reply') ? RC.caution[50] : RC.tint[60],
                color: s.includes('No reply') ? RC.caution[700] : RC.shade[820],
              }}>{s}</span>
            </React.Fragment>
          ))}
        </div>

        <ReceiptLine label="Why here" text={r.whyHere}/>
        <ReceiptLine label="How found" text={blunt ? r.howBlunt : r.howCalm} strong={blunt && !r.applied}/>
        <ReceiptLine label="They said" text={r.repliedText} italic={r.repliedText !== 'No reply yet.'}/>
        <ReceiptLine label="Score / risk" text={`★ ${r.score} · ${r.risk}`} warn={r.risk !== 'No flags.'}/>
        <ReceiptLine label="Why ready" text={r.whyReady} ready={r.ready} last/>
      </div>
    </div>
  );
}

function ReceiptLine({ label, text, italic, strong, warn, ready, last }) {
  return (
    <div style={{ display:'flex', gap:10, marginBottom: last ? 0 : 7 }}>
      <span style={{ flex:'none', width:74, fontSize:10, fontWeight:700, letterSpacing:'.04em', textTransform:'uppercase', color: RC.shade[600], paddingTop:1 }}>{label}</span>
      <span style={{
        flex:1, fontSize:12.5, lineHeight:1.45,
        color: warn ? RC.caution[700] : ready ? RC.primary[800] : strong ? RC.shade[880] : RC.shade[820],
        fontWeight: strong || ready ? 600 : 400,
        fontStyle: italic ? 'italic' : 'normal',
      }}>{text}</span>
    </div>
  );
}

Object.assign(window, { LayoutReceipt });
