// Screen 6: CC Assistant, Genesys-flavoured contact centre console
// Live-updating agent assist: profile, journey, sentiment, dynamic recommendations
// Consultant speaks → AI listens → recommendations evolve → consultant approves → CRM summary

const CCA_TX = [
  { who: 'system', ts: '00:00', text: 'Handoff received from Hala · full context loaded' },
  { who: 'aria',   ts: '00:01', text: "Hi Amélie, Sarah's been on with me. EK202 cancelled, she chose EK203 direct, but wants to confirm with a human before I make the change. She's verified. I've prepared the action plan on your right." },
  { who: 'consultant', ts: '00:08', text: "Hi Sarah, this is Amélie from Emirates. I have the full context from your conversation with Hala. Just to make sure I have everything, you'd like EK203 tonight, direct, seat 23A, vegetarian meal carried over, with priority disruption handling enabled. Is that all correct?" },
  { who: 'sarah',  ts: '00:21', text: "Yes, exactly that.", sent: 'pos' },
  { who: 'consultant', ts: '00:24', text: "Perfect. Quick check, anything else worrying you about the new flight before I confirm it?" },
  { who: 'sarah',  ts: '00:30', text: "Just one thing, I want to make sure my Skywards Miles still credit for this leg.", sent: 'neutral' },
  { who: 'consultant', ts: '00:36', text: "Good question. Let me check that for you." },
];

// Wrap-up dialogue after Miles answer + approval
const CCA_WRAPUP = [
  { who: 'consultant', ts: '00:48', text: "Yes, confirmed. You'll earn the same Miles on EK203 as you would have on EK202. Distance is identical." },
  { who: 'sarah',      ts: '00:54', text: "Great. Then please go ahead." },
];

const CCA_GOODBYE = [
  { who: 'consultant', ts: '01:14', text: "All done, Sarah. EK203 is confirmed, seat 23A is yours, meal preference and priority handling are on. Confirmation just landed in your WhatsApp and email." },
  { who: 'sarah',      ts: '01:24', text: "Thank you so much, Amélie. That was honestly the easiest rebooking I've ever had." },
  { who: 'consultant', ts: '01:30', text: "I'm so glad to hear that. Have a wonderful trip and a great meeting tomorrow. Safe travels with Emirates." },
  { who: 'sarah',      ts: '01:38', text: "Thanks, you too. Bye!" },
  { who: 'consultant', ts: '01:40', text: "Goodbye, Sarah." },
  { who: 'system',     ts: '01:42', text: 'Call ended · 1m 42s · Wrapping up CRM' },
];

const ACTIONS = [
  { id: 'rebook',  head: 'Rebook PNR MTCHL7 → EK203', meta: 'booking.update · 1 write' },
  { id: 'seat',    head: 'Reserve seat 23A on EK203', meta: 'seat.assign · 1 write' },
  { id: 'meal',    head: 'Transfer AVML meal preference', meta: 'profile.preference · 1 write' },
  { id: 'priority',head: 'Enable priority disruption handling', meta: 'flag.set · 1 write' },
  { id: 'notify',  head: 'Send confirmation · WhatsApp + email', meta: 'notify.send · 2 writes' },
];

// Next Best Action evolves with conversation turns
const NBA_BY_STEP = [
  { step: 0, focus: 'Greet & confirm context',     hint: 'Customer escalated mid-conversation. Acknowledge handoff, do not re-verify.' },
  { step: 2, focus: 'Read back the plan',          hint: 'Sarah expects you to know everything. Recap EK203 + seat + meal + priority.' },
  { step: 4, focus: 'Surface remaining concerns',  hint: 'Open the floor before approving. She paused before agreeing earlier.' },
  { step: 6, focus: 'Answer Miles credit question',hint: 'Policy DOC-2024-IRR-04 confirms identical Miles on Emirates-initiated rebookings.' },
  { step: 8, focus: 'Approve & execute 5 actions', hint: 'All blockers cleared. Customer is ready. Execute the prepared plan.' },
  { step: 9, focus: 'Wrap-up & warm goodbye',      hint: 'Confirmation sent. Close with appreciation, set tone for the trip.' },
];

function CopilotScreen({ onAdvance, autoAdvance }) {
  const [step, setStep]   = React.useState(0);              // transcript progression
  const [confirming, setConfirming] = React.useState(false);
  const [confirmed,  setConfirmed]  = React.useState(false);
  const [done, setDone] = React.useState({});               // executed action ids
  const [showSummary, setShowSummary] = React.useState(false);
  const [milesAnswered, setMilesAnswered] = React.useState(false);
  const [goodbyeStep, setGoodbyeStep] = React.useState(0);
  const [scale, setScale] = React.useState(1);
  const txRef = React.useRef(null);

  // scale to viewport
  React.useEffect(() => {
    const recalc = () => {
      const sx = (window.innerWidth - 40) / 1480;
      const sy = (window.innerHeight - 40) / 940;
      setScale(Math.min(sx, sy, 1));
    };
    recalc();
    window.addEventListener('resize', recalc);
    return () => window.removeEventListener('resize', recalc);
  }, []);

  // auto-progress transcript at human speech speed
  React.useEffect(() => {
    if (step >= CCA_TX.length) return;
    const delays = [1800, 4400, 5200, 2600, 3200, 3800, 2800];
    const t = setTimeout(() => setStep(s => s + 1), delays[step] || 3000);
    return () => clearTimeout(t);
  }, [step]);

  React.useEffect(() => {
    if (step === CCA_TX.length) {
      const t = setTimeout(() => setMilesAnswered(true), 2600);
      return () => clearTimeout(t);
    }
  }, [step]);

  // After confirmation, run goodbye sequence one line at a time
  React.useEffect(() => {
    if (!confirmed) return;
    if (goodbyeStep >= CCA_GOODBYE.length) return;
    const delays = [3200, 3600, 3400, 2400, 2000, 1800];
    const t = setTimeout(() => setGoodbyeStep(s => s + 1), delays[goodbyeStep] || 2800);
    return () => clearTimeout(t);
  }, [confirmed, goodbyeStep]);

  React.useEffect(() => {
    if (txRef.current) txRef.current.scrollTop = txRef.current.scrollHeight;
  }, [step, milesAnswered, goodbyeStep, confirmed]);

  const handleConfirm = () => {
    if (confirming || confirmed) return;
    setConfirming(true);
    ACTIONS.forEach((a, i) => {
      setTimeout(() => setDone(d => ({ ...d, [a.id]: true })), 500 + i * 500);
    });
    setTimeout(() => {
      setConfirming(false);
      setConfirmed(true);
      // Show summary after the goodbye sequence finishes
      setTimeout(() => setShowSummary(true), 18000);
      if (autoAdvance) setTimeout(() => onAdvance && onAdvance(), 26000);
    }, 500 + ACTIONS.length * 500 + 400);
  };

  const visibleTx = CCA_TX.slice(0, step);

  // Progress index for NBA evolution
  const progressIdx =
    confirmed && goodbyeStep >= CCA_GOODBYE.length - 1 ? 9 :
    confirmed ? 8 :
    milesAnswered ? 6 :
    step >= 5 ? 4 :
    step >= 3 ? 2 :
    0;
  const currentNBA = NBA_BY_STEP.slice().reverse().find(n => progressIdx >= n.step) || NBA_BY_STEP[0];

  return (
    <div className="gx" style={{transform:`scale(${scale})`, transformOrigin:'top left'}}>
      {/* Top toolbar */}
      <div className="gx-bar">
        <div className="brand">
          <div className="gx-logo">CX</div>
          <span>Cloud Contact Centre</span>
          <span className="sep">·</span>
          <span className="app">CC Assistant</span>
          <span className="powered-genesys" title="Powered by Genesys">
            <span className="gen-text">on</span>
            <img src="assets/genesys-logo.png" alt="Genesys" className="gen-logo" />
          </span>
        </div>
        <div className="nav-pills">
          <div className="nav-pill active">My Workspace</div>
          <div className="nav-pill">Performance</div>
          <div className="nav-pill">Knowledge</div>
          <div className="nav-pill">Admin</div>
        </div>
        <div className="grow"></div>
        <div className="agent-state"><span className="dot"></span> On Call</div>
        <div className="agent-info">
          <div className="av"><img src="assets/consultant.svg" alt="Amélie Laurent" /></div>
          <div className="meta">
            <div className="n">Amélie Laurent</div>
            <div className="r">Senior Consultant · Customer Care</div>
          </div>
        </div>
      </div>

      {/* Interaction strip */}
      <div className="gx-strip">
        <div className="ix-pill active">
          <div className="ch"><Icon.phone size={12} /></div>
          <div>
            <div className="name">Sarah Mitchell · Voice</div>
            <div className="meta">Transferred from Hala · 00:42 ago</div>
          </div>
        </div>
        <div className="ix-pill" style={{opacity:0.55}}>
          <div className="ch"><Icon.chat size={12} /></div>
          <div>
            <div className="name">Imran Ali · Chat</div>
            <div className="meta">On hold</div>
          </div>
        </div>
        <div className="timer-pill">
          <span className="rec"></span>
          <span>REC</span>
          <span className="t">00:42</span>
        </div>
        <div className="actions-icons">
          <div className="ic" title="Mute"><Icon.mute size={14} /></div>
          <div className="ic" title="Hold"><Icon.keypad size={14} /></div>
          <div className="ic" title="Transfer"><Icon.refresh size={14} /></div>
          <div className="ic danger" title="End"><Icon.endcall size={14} /></div>
        </div>
      </div>

      {/* Body grid */}
      <div className="gx-body">
        {/* LEFT, Profile + Sentiment + Journey */}
        <div className="gx-pane gx-profile-pane">
          <div className="gx-pane-head">Customer 360</div>
          <div className="scroll">

            <div className="gx-profile-card">
              <div className="gx-profile-head">
                <div className="av"><img src="assets/sarah.svg" alt="Sarah" /></div>
                <div>
                  <div className="nm">Sarah Mitchell</div>
                  <div className="tier">◆ Skywards Silver · since 2019</div>
                  <div className="age">Customer of 6 yrs · 23 trips</div>
                </div>
              </div>

              <div className="gx-kv">
                <div className="k">Booking</div>
                <div className="v"><span className="mono">MTCHL7</span></div>
                <div className="k">Phone</div>
                <div className="v"><span className="mono">+971 50 ••• 4127</span></div>
                <div className="k">Email</div>
                <div className="v">sarah.mitchell@gmail.com</div>
                <div className="k">Lifetime value</div>
                <div className="v">AED 47,200</div>
                <div className="k">Languages</div>
                <div className="v">EN · FR</div>
              </div>

              <div className="gx-divider"></div>

              <div style={{fontSize:10.5, color:'var(--gx-text-2)', textTransform:'uppercase', letterSpacing:'0.1em', fontWeight:700, marginBottom:6}}>Segments</div>
              <div className="gx-tag-row">
                <span className="gx-tag">Frequent NYC</span>
                <span className="gx-tag good">Mobile-first</span>
                <span className="gx-tag">Prefers chat</span>
                <span className="gx-tag warn">Time-sensitive trip</span>
              </div>
            </div>

            {/* Redesigned sentiment card */}
            <div className="gx-sent-card">
              <div className="gx-sent-head">
                <div className="lbl">Sentiment · live</div>
                <span className="live-dot"><span></span> tracking</span>
              </div>
              {(() => {
                const sentPct = confirmed ? 92 : milesAnswered ? 72 : step >= 4 ? 56 : step >= 2 ? 42 : 28;
                const sentLbl = confirmed ? 'Delighted' : milesAnswered ? 'Reassured' : step >= 4 ? 'Engaged' : step >= 2 ? 'Cautious' : 'Concerned';
                const sentCls = confirmed ? 'pos' : milesAnswered ? 'imp' : step >= 4 ? 'imp' : step >= 2 ? 'cau' : 'con';
                const sentTrend = confirmed ? '+64' : milesAnswered ? '+44' : step >= 4 ? '+28' : step >= 2 ? '+14' : '0';
                const sentColor = confirmed ? '#4ADE80' : milesAnswered ? '#60A5FA' : step >= 4 ? '#93C5FD' : step >= 2 ? '#FCD34D' : '#FCA5A5';
                // Flat SVG face icon, mood determined by mouth path + brow
                const SentFace = () => {
                  // 5 moods: 0 worried, 1 cautious, 2 neutral, 3 reassured, 4 delighted
                  const mood = confirmed ? 4 : milesAnswered ? 3 : step >= 4 ? 2 : step >= 2 ? 1 : 0;
                  const mouthPaths = [
                    'M16 30 Q24 24 32 30',  // worried (frown)
                    'M16 28 Q24 26 32 28',  // cautious (slight frown/flat)
                    'M16 28 L32 28',        // neutral (line)
                    'M16 27 Q24 31 32 27',  // reassured (small smile)
                    'M14 26 Q24 34 34 26',  // delighted (big smile)
                  ];
                  const eyeY = mood >= 3 ? 18 : 19;
                  const browY1 = mood === 0 ? 14 : mood === 1 ? 15 : 13;
                  const browY2 = mood === 0 ? 12 : mood === 1 ? 13 : 13;
                  return (
                    <svg viewBox="0 0 48 48" width="44" height="44" fill="none">
                      <circle cx="24" cy="24" r="22" fill={sentColor} opacity="0.18" />
                      <circle cx="24" cy="24" r="22" stroke={sentColor} strokeWidth="1.5" opacity="0.5" />
                      {/* eyes */}
                      <circle cx="18" cy={eyeY} r="2" fill={sentColor} />
                      <circle cx="30" cy={eyeY} r="2" fill={sentColor} />
                      {/* brows */}
                      {mood <= 1 && (
                        <>
                          <path d={`M14 ${browY1} L21 ${browY2}`} stroke={sentColor} strokeWidth="1.5" strokeLinecap="round" />
                          <path d={`M27 ${browY2} L34 ${browY1}`} stroke={sentColor} strokeWidth="1.5" strokeLinecap="round" />
                        </>
                      )}
                      {/* mouth */}
                      <path d={mouthPaths[mood]} stroke={sentColor} strokeWidth="2.2" strokeLinecap="round" fill="none" />
                    </svg>
                  );
                };
                const reasonText = confirmed
                  ? 'All blockers cleared. Customer thanked you by name. Strong positive close.'
                  : milesAnswered
                  ? 'Skywards Miles question answered. Tone is opening up, ready to confirm.'
                  : step >= 4
                  ? 'You acknowledged her plan without making her repeat it. Trust is building.'
                  : step >= 2
                  ? 'Disruption + Manhattan deadline + channel switch. She is testing whether you know.'
                  : 'Just escalated from voice with Hala. Time pressure makes this fragile.';
                const drivers = confirmed
                  ? [{ k: 'Confidence in plan', v: 'high' }, { k: 'Personal connection', v: 'high' }, { k: 'Time pressure', v: 'low' }]
                  : milesAnswered
                  ? [{ k: 'Confidence in plan', v: 'high' }, { k: 'Open concerns', v: 'none' }, { k: 'Time pressure', v: 'mid' }]
                  : step >= 4
                  ? [{ k: 'Context awareness', v: 'high' }, { k: 'Open concerns', v: '1' }, { k: 'Time pressure', v: 'mid' }]
                  : [{ k: 'Open concerns', v: '2+' }, { k: 'Channel switches', v: '3' }, { k: 'Time pressure', v: 'high' }];
                return <>
                  <div className="gx-sent-hero">
                    <div className="gx-sent-emoji"><SentFace /></div>
                    <div className="gx-sent-meta">
                      <div className={`gx-sent-status ${sentCls}`}>{sentLbl}</div>
                      <div className="gx-sent-num">
                        <span className="big">{sentPct}</span>
                        <span className="suf">/100</span>
                        <span className={`delta ${sentTrend === '0' ? 'flat' : 'up'}`}>{sentTrend !== '0' && '↑'} {sentTrend}</span>
                      </div>
                    </div>
                  </div>
                  <div className="gx-sent-bar-v2">
                    <div className="bar-track">
                      <div className={`bar-fill ${sentCls}`} style={{width: sentPct + '%'}}></div>
                    </div>
                    <div className="bar-marks">
                      <span style={{left:'25%'}}></span>
                      <span style={{left:'50%'}}></span>
                      <span style={{left:'75%'}}></span>
                    </div>
                  </div>
                  <div className="gx-sent-reason">{reasonText}</div>
                  <div className="gx-sent-drivers">
                    {drivers.map((d, i) => (
                      <div key={i} className="driver-row">
                        <span className="dk">{d.k}</span>
                        <span className={`dv v-${d.v.replace('+','')}`}>{d.v}</span>
                      </div>
                    ))}
                  </div>
                </>;
              })()}
            </div>

            <div className="gx-journey-card">
              <div className="ttl">Conversation Journey</div>
              <div className="gx-journey">
                <div className="step done">
                  <div className="bullet"><Icon.envelope size={11} /></div>
                  <div className="meta">
                    <div className="label">Email opened <span className="ts">09:14</span></div>
                    <div className="desc">Cancellation notice · EK202</div>
                  </div>
                </div>
                <div className="step done">
                  <div className="bullet"><Icon.chat size={11} /></div>
                  <div className="meta">
                    <div className="label">WhatsApp <span className="ts">09:16–20</span></div>
                    <div className="desc">12 messages with Hala · 2 options reviewed</div>
                  </div>
                </div>
                <div className="step done">
                  <div className="bullet"><Icon.phone size={11} /></div>
                  <div className="meta">
                    <div className="label">Voice with Hala <span className="ts">09:21–24</span></div>
                    <div className="desc">Verified · clarified meal/lounge/risk</div>
                  </div>
                </div>
                <div className="step active">
                  <div className="bullet"><Icon.user size={11} /></div>
                  <div className="meta">
                    <div className="label">Voice with Amélie <span className="ts">09:24–now</span></div>
                    <div className="desc">{confirmed ? 'Confirmation sent · wrap-up' : 'Confirming rebook'}</div>
                  </div>
                </div>
                <div className={`step ${confirmed ? 'done' : ''}`}>
                  <div className="bullet">5</div>
                  <div className="meta">
                    <div className="label">Resolution & follow-up</div>
                    <div className="desc">Confirmation sent · trip monitored</div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>

        {/* CENTER, Live transcript */}
        <div className="gx-pane gx-tx-pane">
          <div className="gx-pane-head">
            Live Transcript
            <span className="live"><span className="d"></span> LIVE · ASR</span>
          </div>
          <div className="scroll" ref={txRef}>
            {visibleTx.map((line, i) => {
              if (line.who === 'system') {
                return <div key={i} className="gx-tx-line system"><div className="head"><span className="badge">SYSTEM</span><span className="ts">{line.ts}</span></div><div className="text">{line.text}</div></div>;
              }
              const cls = line.who;
              const label = line.who === 'aria' ? 'HALA · AI' : line.who === 'consultant' ? 'AMÉLIE' : 'SARAH · PAX';
              const isLast = i === visibleTx.length - 1;
              return (
                <div key={i} className={`gx-tx-line ${cls} ${isLast ? 'live' : ''}`}>
                  <div className="head">
                    <span className="badge">{label}</span>
                    <span className="ts">{line.ts}</span>
                  </div>
                  <div className="text">{line.text}</div>
                </div>
              );
            })}
            {milesAnswered && CCA_WRAPUP.map((line, i) => (
              <div key={`w-${i}`} className={`gx-tx-line ${line.who}`}>
                <div className="head">
                  <span className="badge">{line.who === 'consultant' ? 'AMÉLIE' : 'SARAH · PAX'}</span>
                  <span className="ts">{line.ts}</span>
                </div>
                <div className="text">{line.text}</div>
              </div>
            ))}
            {confirmed && (
              <div className="gx-tx-line system">
                <div className="head"><span className="badge">SYSTEM</span><span className="ts">01:08</span></div>
                <div className="text">✓ Booking updated by Amélie Laurent · EK203 confirmed · Confirmation dispatched</div>
              </div>
            )}
            {confirmed && CCA_GOODBYE.slice(0, goodbyeStep).map((line, i) => {
              if (line.who === 'system') {
                return <div key={`g-${i}`} className="gx-tx-line system"><div className="head"><span className="badge">SYSTEM</span><span className="ts">{line.ts}</span></div><div className="text">{line.text}</div></div>;
              }
              return (
                <div key={`g-${i}`} className={`gx-tx-line ${line.who}`}>
                  <div className="head">
                    <span className="badge">{line.who === 'consultant' ? 'AMÉLIE' : 'SARAH · PAX'}</span>
                    <span className="ts">{line.ts}</span>
                  </div>
                  <div className="text">{line.text}</div>
                </div>
              );
            })}

            {/* AI listening indicator */}
            {!confirmed && (
              <div className="gx-listening">
                <div className="wave"><span></span><span></span><span></span><span></span><span></span></div>
                <span>AI Assist is listening, recommendation panel updates as the call continues.</span>
              </div>
            )}
          </div>
        </div>

        {/* RIGHT, AI Recommendations */}
        <div className="gx-pane gx-rec-pane">
          <div className="gx-pane-head">
            AI Assist · Next Best Action
            <span className="live" style={{background:'rgba(255,79,31,0.15)', color:'var(--gx-accent)'}}>
              <span className="d" style={{background:'var(--gx-accent)'}}></span> READY
            </span>
          </div>

          <div className="scroll">

            {/* Live NBA hint card, evolves with conversation */}
            <div className="gx-nba-hint">
              <div className="hint-head">
                <span className="step-num">{Math.min(progressIdx + 1, 9)}</span>
                <span className="hint-title">{currentNBA.focus}</span>
              </div>
              <div className="hint-body">{currentNBA.hint}</div>
            </div>

            <div className="gx-rec-card featured">
              <div className="nba"><Icon.bolt size={11} /> Recommended</div>
              <div className="ttl">Rebook to EK203 · Direct</div>
              <div className="route">DXB 22:40 → JFK 04:55 · 28→29 Apr</div>

              {/* Approve button at top */}
              <div className="gx-rec-actions top">
                <button
                  className={`gx-btn-confirm ${confirmed ? 'confirmed' : ''} ${milesAnswered && !confirming && !confirmed ? 'ready' : ''}`}
                  onClick={handleConfirm}
                  disabled={confirming || confirmed}
                >
                  {confirming
                    ? <><span className="gx-btn-spinner"></span> Executing 5 actions…</>
                    : confirmed
                      ? <><Icon.check size={14} /> Confirmed by Amélie</>
                      : <><Icon.check size={14} /> Approve & execute all 5</>}
                </button>
                <div className="gx-ghost-row">
                  <button className="gx-btn-ghost" disabled={confirmed}>Modify</button>
                  <button className="gx-btn-ghost" disabled={confirmed}>Reject</button>
                  <button className="gx-btn-ghost" disabled={confirmed}>Escalate</button>
                </div>
              </div>

              {/* Scrollable detail area */}
              <div className="gx-rec-scroll">
                <div className="tags-line">
                  <span className="pill good">No fare diff</span>
                  <span className="pill">Same cabin</span>
                  <span className="pill">12 seats</span>
                  <span className="pill">Seat 23A held</span>
                </div>

                <div className="gx-why">
                  <div className="lbl">Why this option</div>
                  <ul>
                    <li>Customer chose explicitly during voice call (00:21)</li>
                    <li>Lands ~6h before her 11:00 NYC meeting</li>
                    <li>No price difference, no commercial decision needed</li>
                    <li>Schedule reliability: 28 of last 30 days on time</li>
                    <li>Skywards Miles credit confirmed identical (verified 00:48)</li>
                  </ul>
                </div>

                <div className="gx-checklist">
                  <div className="lbl">Actions on approval</div>
                  {ACTIONS.map((a, i) => (
                    <div key={a.id} className={`gx-act-item ${done[a.id] ? 'done' : ''}`}>
                      <div className="num">{done[a.id] ? <Icon.check size={11} /> : i + 1}</div>
                      <div className="info">
                        <div className="head">{a.head}</div>
                        <div className="meta">{a.meta}</div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>

            {/* Secondary card, knowledge */}
            <div className="gx-rec-card knowledge-card">
              <div className="kw-head">Knowledge · auto-fetched</div>
              <div className="kw-title">Skywards Miles on rebooked flights</div>
              <div className="kw-body">
                Miles credit equal to original flight when rebooking is initiated by Emirates due to operational disruption. Customer keeps tier benefits.
              </div>
              <div className="kw-source">Source: Policy DOC-2024-IRR-04</div>
            </div>

            <div className="gx-rec-card knowledge-card">
              <div className="kw-head">Next likely question</div>
              <div className="kw-title quote">"Will I be notified if EK203 also has issues?"</div>
              <div className="kw-body">
                <strong>Suggested answer:</strong> Yes, priority disruption flag is being set. App push, SMS and email notifications enabled.
              </div>
            </div>

          </div>
        </div>

      </div>

      {/* Footer */}
      <div className="gx-foot">
        <div className="item"><span className="ok">●</span> Audit log: 14 events</div>
        <div className="item"><span className="ok">●</span> All actions within policy scope</div>
        <div className="item"><span className="ok">●</span> PII auto-redacted</div>
        <div className="grow"></div>
        <div className="item">cc-assistant.emirates.com</div>
        <div className="item">v 4.12.0</div>
      </div>

      {/* End-of-call CRM summary */}
      {showSummary && <CCASummary onClose={() => onAdvance && onAdvance()} />}
    </div>
  );
}

function CCASummary({ onClose }) {
  return (
    <div className="gx-summary-modal">
      <div className="sheet">
        <div className="sheet-head">
          <div className="title">
            <div className="ico"><Icon.check size={16} /></div>
            <span>Interaction wrapped · CRM auto-populated</span>
          </div>
          <div className="meta">CASE-2026-0428-1147 · 1m 42s handle time · Closed by Amélie Laurent</div>
        </div>

        <div className="sheet-body">
          {/* LEFT */}
          <div>
            <div className="gx-sum-block" style={{marginBottom:14}}>
              <div className="block-ttl"><Icon.doc size={12} /> Case Narrative <span style={{marginLeft:'auto', fontSize:9, color:'var(--gx-accent)', fontWeight:700, letterSpacing:'0.06em'}}>AI-DRAFTED</span></div>
              <div className="block-body">
                <div className="narrative">
                  Customer's flight EK202 (DXB→JFK, 28 Apr) was cancelled due to operational disruption. Customer had a time-critical meeting in NYC on 29 Apr at 11:00. Conversation began on email at 09:14, moved to WhatsApp at 09:16 with Hala (AI), where Hala presented two alternatives. Customer requested human verification and was transferred to Amélie Laurent at 09:24. Amélie confirmed Sarah's preferred option, EK203 (DXB 22:40 → JFK 04:55, direct), addressed her one remaining concern about Skywards Miles credit, and approved the prepared 5-action plan. All actions executed successfully. Customer expressed strong appreciation at close. No fare difference applied.
                </div>
              </div>
            </div>

            <div className="gx-sum-block" style={{marginBottom:14}}>
              <div className="block-ttl">Resolution Actions</div>
              <div className="block-body">
                <ul>
                  <li>Rebooked PNR MTCHL7 from EK202 → EK203</li>
                  <li>Reserved seat 23A on EK203</li>
                  <li>Transferred AVML (vegetarian) meal preference</li>
                  <li>Enabled priority disruption handling flag on profile</li>
                  <li>Sent confirmation via WhatsApp + email</li>
                </ul>
              </div>
            </div>

            <div className="gx-sum-block">
              <div className="block-ttl">Customer Quotes (highlights)</div>
              <div className="block-body">
                <div style={{fontSize:12.5, lineHeight:1.55, color:'var(--gx-text-2)', fontStyle:'italic'}}>
                  <div style={{padding:'4px 0'}}>"I want to make sure my Skywards Miles still credit for this leg."</div>
                  <div style={{padding:'4px 0'}}>"Then please go ahead." <span style={{fontStyle:'normal', color:'var(--gx-good)'}}>(approval)</span></div>
                  <div style={{padding:'4px 0'}}>"That was honestly the easiest rebooking I've ever had." <span style={{fontStyle:'normal', color:'var(--gx-good)'}}>(close)</span></div>
                </div>
              </div>
            </div>
          </div>

          {/* RIGHT */}
          <div>
            <div className="gx-sum-block" style={{marginBottom:14}}>
              <div className="block-ttl">Case Fields</div>
              <div className="block-body">
                <div className="gx-sum-fields">
                  <div className="k">Case ID</div><div className="v">CASE-26-0428-1147</div>
                  <div className="k">PNR</div><div className="v">MTCHL7</div>
                  <div className="k">Customer</div><div className="v" style={{fontFamily:'inherit'}}>Sarah Mitchell</div>
                  <div className="k">Tier</div><div className="v" style={{fontFamily:'inherit'}}>Skywards Silver</div>
                  <div className="k">Reason</div><div className="v" style={{fontFamily:'inherit'}}>IRR · Cancel</div>
                  <div className="k">Resolution</div><div className="v" style={{fontFamily:'inherit'}}>Rebook · same cabin</div>
                  <div className="k">Channel path</div><div className="v" style={{fontFamily:'inherit'}}>Email → WA → Voice</div>
                  <div className="k">Handled by</div><div className="v" style={{fontFamily:'inherit'}}>Hala (AI) → Amélie L.</div>
                  <div className="k">AI handle time</div><div className="v">07:24</div>
                  <div className="k">Human handle time</div><div className="v">01:42</div>
                  <div className="k">Total elapsed</div><div className="v">10:54</div>
                  <div className="k">Final sentiment</div><div className="v" style={{color:'var(--gx-good)', fontFamily:'inherit'}}>92 / Delighted</div>
                </div>
              </div>
            </div>

            <div className="gx-sum-block" style={{marginBottom:14}}>
              <div className="block-ttl">Auto-Tags <span style={{marginLeft:'auto', fontSize:9, color:'var(--gx-accent)', fontWeight:700, letterSpacing:'0.06em'}}>AI-CLASSIFIED</span></div>
              <div className="block-body">
                <div className="gx-crm-tags">
                  <span className="gx-crm-tag">irr-rebook</span>
                  <span className="gx-crm-tag">tier-silver</span>
                  <span className="gx-crm-tag">multi-channel</span>
                  <span className="gx-crm-tag">ai-to-human-handoff</span>
                  <span className="gx-crm-tag">no-fare-diff</span>
                  <span className="gx-crm-tag">first-touch-resolved</span>
                  <span className="gx-crm-tag">policy-compliant</span>
                  <span className="gx-crm-tag">positive-close</span>
                </div>
              </div>
            </div>

            <div className="gx-sum-block">
              <div className="block-ttl">Follow-ups Scheduled</div>
              <div className="block-body">
                <ul>
                  <li>T-2h before EK203: app push status check</li>
                  <li>Post-arrival JFK: CSAT survey via email</li>
                  <li>Continuous: trip monitor active, alert on any schedule change</li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <div className="sheet-foot">
          <div className="left">
            <span className="sync-dot"></span>
            <span>Synced to Genesys CCaaS · Skywards profile · Reservations system</span>
          </div>
          <div className="right">
            <button className="btn">Edit narrative</button>
            <button className="btn">Save & next</button>
            <button className="btn primary" onClick={onClose}>Wrap up call</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function ClosingScreen() {
  const [scale, setScale] = React.useState(1);
  React.useEffect(() => {
    const recalc = () => {
      const sx = (window.innerWidth - 40) / 1440;
      const sy = (window.innerHeight - 40) / 900;
      setScale(Math.min(sx, sy, 1));
    };
    recalc();
    window.addEventListener('resize', recalc);
    return () => window.removeEventListener('resize', recalc);
  }, []);
  return (
    <div className="closing" style={{transform: `scale(${scale})`, flexShrink: 0}}>
      <div className="closing-head">
        <div className="eyebrow">Closing summary</div>
        <h1>What just happened, and what it means</h1>
      </div>
      <div className="closing-grid">
        <div className="closing-col">
          <h3>The Customer Story</h3>
          <div className="compare-block">
            <span className="label before">Today (pre-AI)</span>
            <ul>
              <li>Auto-rebook email arrives, lands her on a poor option</li>
              <li>Calls contact centre, IVR menu, ~22 min wait</li>
              <li>Re-explains booking, name, problem from scratch</li>
              <li>Hears policy, hears a few options, decides under pressure</li>
              <li>Booking changed, no real confirmation of preferences</li>
            </ul>
            <div className="total">~30 minutes · high friction</div>
          </div>
          <div className="compare-block">
            <span className="label after">With Hala</span>
            <ul>
              <li>Email cancellation, but a clear next step on WhatsApp</li>
              <li>Hala greets her with full context, two curated options · 4 min</li>
              <li>One-tap escalation to voice with Hala, no IVR, no wait · 3 min</li>
              <li>Warm transfer to Amélie, who already has the plan ready</li>
              <li>Approved in 1m 42s, confirmation lands instantly</li>
            </ul>
            <div className="total">~10 minutes · never repeats herself</div>
          </div>
        </div>
        <div className="closing-col">
          <h3>The Consultant's Day</h3>
          <div className="compare-block">
            <span className="label before">Consultant today</span>
            <ul>
              <li>Avg handle time: ~9.5 min per call</li>
              <li>Re-explaining vs resolving: ~60% of every call</li>
              <li>Daily call volume: ~40 calls, mostly information gathering</li>
              <li>Most repetitive task: verifying the customer, reading their booking</li>
            </ul>
          </div>
          <div className="compare-block">
            <span className="label after">Consultant with Hala</span>
            <ul>
              <li>Handoff handle time: 1m 42s for this case</li>
              <li>Time spent re-explaining: ~5%, full context handed over</li>
              <li>Daily resolution capacity: 4–6× higher</li>
              <li>Role shifts from triage handler to senior decision-maker</li>
            </ul>
          </div>
        </div>
        <div className="closing-col">
          <h3>The Data You Now Have</h3>
          <ul className="data-list">
            <li><div className="head">Structured conversation records</div><div className="desc">Every channel, every turn, fully searchable</div></li>
            <li><div className="head">AI recommendations + acceptance rates</div><div className="desc">Continuous improvement of options offered</div></li>
            <li><div className="head">Sentiment over time per customer</div><div className="desc">Predict friction before it escalates</div></li>
            <li><div className="head">Tool call logs + decision paths</div><div className="desc">Audit any action in two clicks</div></li>
            <li><div className="head">Channel preferences per segment</div><div className="desc">Personalise outreach per passenger</div></li>
            <li><div className="head">Aggregate operational signals</div><div className="desc">See where to invest in the experience next</div></li>
          </ul>
        </div>
      </div>
      <div className="closing-foot">
        <p>
          <strong>One agent. Three channels. One passenger. One booking.</strong><br/>
          And your human consultant, always, irreversibly, in control of every change.
        </p>
      </div>
    </div>
  );
}

window.CopilotScreen = CopilotScreen;
window.ClosingScreen = ClosingScreen;
