// ============================================================
//   LayoutCopilot — "Co-pilot Chat"
//   The violent move: the AI is the page.
//   Left = a conversation with your AI recruiter.
//   Right = whatever the AI is currently showing you.
//   The pipeline, the candidate list, the detail panel — all
//   collapse into the thread. You don't navigate; you ask.
//
//   The argument: FactoryFix isn't an ATS with AI sprinkled in.
//   It's a chat with an AI that uses an ATS as scaffolding.
// ============================================================
const { color: COC } = window.FF;

const SEED_THREAD = [
  { who:'ai',   t:'9:02 AM', text:"Good morning. I've been busy.", subtle:true },
  { who:'ai',   t:'9:02 AM', text:"Overnight I sourced 17 new candidates for Machine Operator I, sent 23 first-touch SMS messages, and got 9 replies. Three of them are worth your time. Want me to walk you through them?" },
  { who:'me',   t:'9:04 AM', text:"yeah show me" },
  { who:'ai',   t:'9:04 AM', text:"Here's the strongest reply.", card:'c18' },
  { who:'ai',   t:'9:04 AM', text:"Marcus came in cold this morning. I asked about shift and pay; he wants 2nd shift, says $20+ works. He's a clean match — no prior history with us, score 4.6, 12 minutes away. I'd advance him." },
  { who:'me',   t:'9:06 AM', text:"schedule him for thursday 2pm" },
  { who:'ai',   t:'9:06 AM', text:"Done — I sent him three slots Thursday afternoon (1, 2, 3pm). He picked 2pm. I'll send the calendar invite once you confirm.", suggest:['Confirm invite','Reschedule','Cancel'] },
  { who:'me',   t:'9:07 AM', text:"confirm" },
  { who:'ai',   t:'9:07 AM', text:"Invite sent. Reminder will fire 1 hour before. Next up — Tania Briggs.", card:'c19' },
];

function LayoutCopilot({ candidates, onExit }) {
  const candidateById = React.useMemo(() => {
    const m = {}; candidates.forEach(c => m[c.id] = c); return m;
  }, [candidates]);

  const [thread, setThread] = React.useState(SEED_THREAD);
  const [input, setInput] = React.useState('');
  const [focus, setFocus] = React.useState('c19'); // candidate shown in context panel
  const scrollRef = React.useRef();

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [thread]);

  const send = () => {
    if (!input.trim()) return;
    const now = new Date().toLocaleTimeString([], { hour:'numeric', minute:'2-digit' });
    setThread(t => [...t, { who:'me', t:now, text: input.trim() }]);
    setInput('');
    setTimeout(() => {
      setThread(t => [...t, { who:'ai', t:now, text:'Got it. Working on that…', subtle:true }]);
    }, 400);
  };

  return (
    <div data-screen-label="Co-pilot Chat" style={{
      position:'fixed', inset:0, zIndex:50,
      background: COC.shade[880], color:'#fff',
      fontFamily:"'Inter',system-ui,sans-serif",
      display:'flex', flexDirection:'column',
    }}>
      <CopilotTopBar onExit={onExit}/>
      <div style={{ flex:1, display:'flex', minHeight:0 }}>
        {/* LEFT — the conversation */}
        <div style={{
          flex:'1 1 60%', display:'flex', flexDirection:'column', minHeight:0,
          borderRight:`1px solid ${COC.shade[860]}`,
        }}>
          <div ref={scrollRef} style={{
            flex:1, overflow:'auto', padding:'24px 28px 12px',
            display:'flex', flexDirection:'column', gap:14,
          }}>
            {thread.map((m, i) => (
              <Message key={i} m={m} candidateById={candidateById} onFocus={setFocus} focusId={focus}/>
            ))}
            <TypingHint/>
          </div>
          <ChatInput value={input} setValue={setInput} onSend={send}/>
        </div>

        {/* RIGHT — the contextual surface (changes based on what AI is talking about) */}
        <div style={{
          flex:'0 0 38%', minWidth:360, display:'flex', flexDirection:'column',
          background:'#0B1226',
        }}>
          <ContextPanel candidate={candidateById[focus]}/>
        </div>
      </div>
    </div>
  );
}

/* ---------- Top bar ---------- */
function CopilotTopBar({ onExit }) {
  return (
    <div style={{
      padding:'16px 28px', borderBottom:`1px solid ${COC.shade[860]}`,
      display:'flex', alignItems:'center', gap:14,
    }}>
      <span style={{
        width:30, height:30, borderRadius:8,
        background: 'linear-gradient(270deg,#ae35f7 -15%,#5f30d1 71%)',
        display:'inline-flex', alignItems:'center', justifyContent:'center', flex:'none',
      }}>
        <span className="ai-dot" style={{ width:8, height:8 }}/>
      </span>
      <div>
        <div style={{ fontSize:14, fontWeight:700, letterSpacing:'-.005em' }}>Your AI recruiter</div>
        <div style={{ fontSize:11, color: COC.copilot[300] }}>● Online · 17 in progress · last reply 4m ago</div>
      </div>
      <div style={{ flex:1 }}/>
      <span style={{
        fontSize:10, fontWeight:700, letterSpacing:'.14em', textTransform:'uppercase',
        color:'rgba(255,255,255,.5)', padding:'3px 9px',
        border:'1px solid rgba(255,255,255,.18)', borderRadius:9999,
      }}>Co-pilot Chat</span>
      <button onClick={onExit} style={{
        padding:'6px 12px', background:'transparent',
        border:`1px solid ${COC.shade[820]}`, borderRadius:6, color:'#fff',
        fontSize:11, fontWeight:600, cursor:'pointer',
        letterSpacing:'.04em', textTransform:'uppercase',
      }}>Esc · Exit</button>
    </div>
  );
}

/* ---------- A message in the thread ---------- */
function Message({ m, candidateById, onFocus, focusId }) {
  if (m.who === 'me') {
    return (
      <div style={{ alignSelf:'flex-end', maxWidth:'70%' }}>
        <div style={{
          padding:'10px 14px', background: COC.shade[860],
          border:`1px solid ${COC.shade[840]}`, borderRadius:'14px 14px 4px 14px',
          fontSize:14, color:'#fff', fontFamily:'ui-monospace,SFMono-Regular,monospace',
        }}>{m.text}</div>
        <div style={{ fontSize:10, color:'rgba(255,255,255,.4)', textAlign:'right', marginTop:3 }}>{m.t}</div>
      </div>
    );
  }
  return (
    <div style={{ maxWidth:'80%', display:'flex', gap:10, alignItems:'flex-start' }}>
      <span style={{
        width:22, height:22, borderRadius:6, flex:'none', marginTop:2,
        background:'linear-gradient(270deg,#ae35f7 -15%,#5f30d1 71%)',
      }}/>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{
          padding:'10px 14px',
          background: m.subtle ? 'rgba(255,255,255,.04)' : COC.shade[860],
          border:`1px solid ${m.subtle ? 'rgba(255,255,255,.05)' : COC.shade[840]}`,
          borderRadius:'14px 14px 14px 4px',
          fontSize:14, lineHeight:1.5, color: m.subtle ? 'rgba(255,255,255,.65)' : '#fff',
        }}>{m.text}</div>
        {m.card && candidateById[m.card] && (
          <InlineCandidateCard c={candidateById[m.card]} active={m.card === focusId} onClick={()=>onFocus(m.card)}/>
        )}
        {m.suggest && (
          <div style={{ display:'flex', gap:6, marginTop:8, flexWrap:'wrap' }}>
            {m.suggest.map((s,i) => (
              <button key={i} style={{
                padding:'5px 12px', background:'rgba(174,53,247,.12)',
                border:`1px solid ${COC.copilot[600]}`, borderRadius:9999,
                color: COC.copilot[300], fontSize:12, fontWeight:600, cursor:'pointer',
              }}>{s}</button>
            ))}
          </div>
        )}
        <div style={{ fontSize:10, color:'rgba(255,255,255,.35)', marginTop:4 }}>{m.t}</div>
      </div>
    </div>
  );
}

/* ---------- Inline candidate card ---------- */
function InlineCandidateCard({ c, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      marginTop:8, width:'100%', textAlign:'left',
      padding:'12px 14px',
      background: active ? 'rgba(174,53,247,.10)' : 'rgba(255,255,255,.03)',
      border:`1px solid ${active ? COC.copilot[600] : 'rgba(255,255,255,.08)'}`,
      borderRadius:10, cursor:'pointer',
      display:'flex', alignItems:'center', gap:12, color:'#fff',
    }}>
      <span style={{
        width:34, height:34, borderRadius:'50%',
        background:'rgba(255,255,255,.08)', color:'#fff',
        display:'inline-flex', alignItems:'center', justifyContent:'center',
        fontSize:12, fontWeight:700, flex:'none',
      }}>{c.name.split(' ').map(s=>s[0]).slice(0,2).join('')}</span>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', gap:8, alignItems:'center' }}>
          <span style={{ fontSize:14, fontWeight:700 }}>{c.name}</span>
          <span style={{ fontSize:11, color: COC.primary[300], fontWeight:700 }}>★{c.score}</span>
        </div>
        <div style={{ fontSize:11.5, color:'rgba(255,255,255,.55)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
          {c.role} at {c.company}
        </div>
      </div>
      <span style={{ fontSize:11, color:'rgba(255,255,255,.45)', flex:'none' }}>{c.loc.split(',')[0]}</span>
    </button>
  );
}

/* ---------- Input ---------- */
function ChatInput({ value, setValue, onSend }) {
  return (
    <div style={{ padding:'12px 28px 22px', borderTop:`1px solid ${COC.shade[860]}` }}>
      <div style={{ display:'flex', gap:6, marginBottom:8, flexWrap:'wrap' }}>
        {['Show me today\'s top 3', 'Who replied?', 'Schedule interviews this week', 'Why this candidate?'].map(q => (
          <button key={q} onClick={()=>setValue(q)} style={{
            padding:'4px 10px', background:'rgba(255,255,255,.05)',
            border:`1px solid ${COC.shade[820]}`, borderRadius:9999,
            color:'rgba(255,255,255,.7)', fontSize:11, fontWeight:500, cursor:'pointer',
          }}>{q}</button>
        ))}
      </div>
      <form onSubmit={e => { e.preventDefault(); onSend(); }} style={{
        display:'flex', alignItems:'center', gap:10,
        padding:'4px 6px 4px 16px', background: COC.shade[860],
        border:`1px solid ${COC.shade[820]}`, borderRadius:12,
      }}>
        <input value={value} onChange={e=>setValue(e.target.value)}
          placeholder="Ask your AI recruiter…"
          style={{
            flex:1, background:'transparent', border:0, outline:'none',
            color:'#fff', fontSize:14, padding:'10px 0',
            fontFamily:'ui-monospace,SFMono-Regular,monospace',
          }}/>
        <button type="submit" style={{
          padding:'8px 14px',
          background:'linear-gradient(270deg,#ae35f7 -15%,#5f30d1 71%)',
          border:0, borderRadius:8, color:'#fff', fontSize:12, fontWeight:700, cursor:'pointer',
          display:'inline-flex', alignItems:'center', gap:5,
        }}>Send <span style={{ fontSize:11, opacity:.8 }}>↵</span></button>
      </form>
    </div>
  );
}

function TypingHint() {
  return null; // placeholder for future "AI is typing…" indicator
}

/* ---------- The right-side context panel ---------- */
function ContextPanel({ candidate: c }) {
  if (!c) return (
    <div style={{ flex:1, display:'flex', alignItems:'center', justifyContent:'center', color:'rgba(255,255,255,.5)', fontSize:13 }}>
      Ask anything to bring up context.
    </div>
  );
  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', minHeight:0 }}>
      <div style={{
        padding:'18px 22px 14px', borderBottom:`1px solid rgba(255,255,255,.05)`,
        display:'flex', alignItems:'center', gap:12,
      }}>
        <span style={{
          width:44, height:44, borderRadius:'50%',
          background:'rgba(255,255,255,.08)',
          display:'inline-flex', alignItems:'center', justifyContent:'center',
          fontSize:15, fontWeight:700, flex:'none',
        }}>{c.name.split(' ').map(s=>s[0]).slice(0,2).join('')}</span>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:16, fontWeight:800, color:'#fff' }}>{c.name}</div>
          <div style={{ fontSize:12, color:'rgba(255,255,255,.55)' }}>{c.role} · {c.loc}</div>
        </div>
        <span style={{
          fontSize:13, fontWeight:800, color: COC.primary[300],
          padding:'4px 8px', background:'rgba(83,213,139,.08)', borderRadius:5,
        }}>★ {c.score}</span>
      </div>

      <div style={{ padding:'18px 22px', flex:1, overflow:'auto' }}>
        <Section label="The match">
          <div style={{ fontSize:13, color:'rgba(255,255,255,.85)', lineHeight:1.5 }}>
            for <strong style={{ color:'#fff' }}>Machine Operator I</strong> · O'Neal Manufacturing<br/>
            <span style={{ color:'rgba(255,255,255,.55)' }}>Greensboro, NC · 2nd shift · $19–22/hr</span>
          </div>
        </Section>

        <Section label="What we said">
          <div style={{ fontSize:13, color:'rgba(255,255,255,.85)', lineHeight:1.5 }}>
            <span style={{ color:'rgba(255,255,255,.4)' }}>AI · 8:42 AM</span><br/>
            "Hi Tania — saw your application for Machine Operator I. We pay $19–22 for 2nd shift, training paid. Interested?"<br/><br/>
            <span style={{ color:'rgba(255,255,255,.4)' }}>Tania · 8:51 AM</span><br/>
            "{c.lastMsg || 'Yes — open to it.'}"
          </div>
        </Section>

        <Section label="Memory">
          <div style={{
            padding:'10px 12px', background:'rgba(96,206,231,.08)',
            border:`1px solid rgba(96,206,231,.25)`, borderRadius:8,
            fontSize:12, color:'#96CEE7',
          }}>◇ Also applied to CNC Setup at Honda Aircraft, March 2026.</div>
        </Section>

        <Section label="What I'd do next">
          <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
            <ActionRow primary text="Send 3 interview slots — Thu/Fri 1–3pm"/>
            <ActionRow text="Ask about reliable transportation"/>
            <ActionRow text="Pull her resume from her CNC application"/>
          </div>
        </Section>
      </div>
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div style={{ marginBottom:18 }}>
      <div style={{
        fontSize:10, fontWeight:700, letterSpacing:'.14em', textTransform:'uppercase',
        color:'rgba(255,255,255,.4)', marginBottom:8,
      }}>{label}</div>
      {children}
    </div>
  );
}

function ActionRow({ text, primary }) {
  return (
    <button style={{
      padding:'8px 12px', textAlign:'left',
      background: primary ? 'rgba(174,53,247,.10)' : 'rgba(255,255,255,.03)',
      border:`1px solid ${primary ? COC.copilot[600] : 'rgba(255,255,255,.06)'}`,
      borderRadius:8, color: primary ? '#fff' : 'rgba(255,255,255,.75)',
      fontSize:12.5, fontWeight: primary ? 600 : 500, cursor:'pointer',
      display:'flex', alignItems:'center', justifyContent:'space-between', gap:8,
    }}>
      <span>{text}</span>
      <span style={{ fontSize:11, opacity:.55 }}>↵</span>
    </button>
  );
}

Object.assign(window, { LayoutCopilot });
