// Call Detail page
const { useState: useStateDet, useMemo: useMemoDet, useEffect: useEffectDet } = React;

function Detail({ onBack }) {
  const { genWave, SENT_BAND, TRANSCRIPT } = window.VI_DATA;
  const [playing, setPlaying] = useStateDet(false);
  const [progress, setProgress] = useStateDet(0.28); // 0..1

  useEffectDet(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setProgress(p => (p >= 1 ? 0 : p + 0.005));
    }, 140);
    return () => clearInterval(id);
  }, [playing]);

  const wave = useMemoDet(() => genWave(20250420, 180), []);
  const playedIdx = Math.floor(progress * wave.length);

  const totalSec = 862; // 14:22
  const curSec = Math.floor(totalSec * progress);
  const fmt = (s) => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`;

  // markers at relative positions
  const markers = [
    { pos: 0.18, cls: 'blue', lbl: 'Deadline stated' },
    { pos: 0.38, cls: '',     lbl: 'PII · address' },
    { pos: 0.55, cls: 'red',  lbl: 'Service miss admitted' },
    { pos: 0.72, cls: 'blue', lbl: '15% credit offered' },
  ];

  return (
    <>
      <div className="call-hero">
        <div className="crumbs"><a onClick={onBack} style={{ cursor: 'pointer' }}>Call Library</a> <span style={{ opacity: .5 }}>›</span> QSC-248193</div>
        <h1>Ridgeview HOA · missed lawn treatment & reschedule</h1>
        <div className="meta">
          <span>Today · 10:42 AM</span>
          <span className="dot"></span>
          <span>14 min 22 sec</span>
          <span className="dot"></span>
          <span>Jordan Mercer · Install Support</span>
          <span className="dot"></span>
          <span>Inbound · Toll-free 8400</span>
          <span className="dot"></span>
          <span style={{ color: 'var(--pos)' }}>● Resolved · credit issued</span>
        </div>
      </div>

      <div className="tab-row">
        {['Overview','Transcript','Analysis','QA form','Audit log'].map((t, i) => (
          <div key={t} className={'tab ' + (i === 0 ? 'on' : '')}>{t}</div>
        ))}
      </div>

      <div className="detail">
        <div className="left">

          {/* Player */}
          <div className="player">
            <div className="top">
              <button className="play" onClick={() => setPlaying(p => !p)}>
                <Icon name={playing ? 'pause' : 'play'} className="i" />
              </button>
              <button className="btn ghost" onClick={() => setProgress(p => Math.max(0, p - 0.02))}>
                <Icon name="back15" />
              </button>
              <button className="btn ghost" onClick={() => setProgress(p => Math.min(1, p + 0.02))}>
                <Icon name="fwd15" />
              </button>
              <div className="time">
                <b>{fmt(curSec)}</b> <span style={{ opacity: .5 }}>/ 14:22</span>
              </div>
              <div className="speed">
                <button>0.75×</button>
                <button className="on">1×</button>
                <button>1.5×</button>
                <button>2×</button>
              </div>
            </div>

            <div className="wave-wrap">
              <div className="wave">
                {wave.map((w, i) => (
                  <i key={i}
                     className={(i < playedIdx ? 'played ' : '') + (w.spk === 0 ? 'agent' : 'cust')}
                     style={{ height: Math.max(3, w.h * 70) + 'px' }} />
                ))}
              </div>
              <div className="sentband">
                {SENT_BAND.map((s, i) => <i key={i} className={s} />)}
              </div>
              <div className="wave-axis">
                <span>00:00</span><span>03:35</span><span>07:11</span><span>10:46</span><span>14:22</span>
              </div>
              <div className="markers">
                {markers.map((m, i) => (
                  <div key={i} className={'mk ' + m.cls} style={{ left: (m.pos * 100) + '%' }}>
                    <div className="lbl">{m.lbl}</div>
                  </div>
                ))}
              </div>
            </div>

            <div className="legend">
              <div className="ll"><span className="sw"></span> Agent</div>
              <div className="ll"><span className="sw" style={{ background: '#7fb3e8' }}></span> Customer</div>
              <div className="ll" style={{ marginLeft: 'auto' }}><span className="sw pos"></span> Positive sentiment</div>
              <div className="ll"><span className="sw neu"></span> Neutral</div>
              <div className="ll"><span className="sw neg"></span> Negative</div>
            </div>
          </div>

          {/* Transcript */}
          <div className="transcript">
            <div className="hd">
              <h3>Transcript</h3>
              <div className="row" style={{ gap: 10 }}>
                <div className="tabs">
                  <button className="on">Diarized</button>
                  <button>Plain</button>
                  <button>Timestamped</button>
                </div>
                <button className="btn"><Icon name="download" /> .vtt</button>
              </div>
            </div>

            {TRANSCRIPT.map((t, i) => {
              const isCust = t.sp === 'Customer';
              const isActive = i === 4; // weather hold line
              return (
                <div key={i} className={'turn ' + (isActive ? 'active' : '')}>
                  <div>
                    <div className="ts">{t.ts}</div>
                    <div className={'sp ' + (isCust ? 'cust' : '')}>{t.sp}</div>
                  </div>
                  <div>
                    <div className="text">
                      {t.highlight
                        ? t.text.split(t.highlight).map((seg, j, arr) => (
                            <React.Fragment key={j}>
                              {seg}
                              {j < arr.length - 1 && <mark className={isCust ? '' : (t.highlight.includes('credit') ? '' : 'red')}>{t.highlight}</mark>}
                            </React.Fragment>
                          ))
                        : t.text}
                    </div>
                    {t.tags && (
                      <div className="tags">
                        {t.tags.map(tag => (
                          <span key={tag} className={'tag ' + (tag.startsWith('PII') ? 'red' : tag === 'Comp offered' ? 'blue' : '')}>{tag}</span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}

            <div style={{ padding: '18px 0', fontSize: 12, color: 'var(--muted)', textAlign: 'center' }}>
              — Transcript continues (11 more turns) —
            </div>
          </div>
        </div>

        {/* Right sidebar */}
        <div className="right">

          <div className="card first">
            <h4>AI Summary</h4>
            <div className="summary">
              <div className="pull">
                Customer called about a missed weekly lawn treatment at Ridgeview HOA. Agent confirmed weather hold, apologized, rescheduled for tomorrow 8–10 AM, and applied a 15% service credit.
              </div>
              <p>Deadline-driven — board walkthrough Saturday. Customer accepted resolution and expressed appreciation for the quick turnaround.</p>
              <button className="btn ghost" style={{ padding: 0, color: 'var(--blue)', fontSize: 12 }}>Expand full summary <Icon name="chevright" style={{ width: 12, height: 12 }} /></button>
            </div>
          </div>

          <div className="card">
            <h4>Customer Intent</h4>
            <div className="intent-tag">
              <span className="dot"></span> Service reschedule
            </div>
            <div className="conf">Confidence 0.94 · 3 secondary: scheduling, compensation, complaint</div>
          </div>

          <div className="card">
            <h4>Speaker Talk-Time</h4>
            <div className="talkratio">
              <div className="a" style={{ width: '58%' }}></div>
              <div className="c" style={{ width: '42%' }}></div>
            </div>
            <div className="talkratio-lbl">
              <span>Agent 58% · 8:18</span>
              <span>Customer 42% · 6:04</span>
            </div>
            <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 12, lineHeight: 1.5 }}>
              Within benchmark (40–60% agent). 2 interruptions, 0 long silences.
            </div>
          </div>

          <div className="card">
            <h4>Topics Discussed</h4>
            {[
              { name: 'Scheduling', n: 14, pct: 100 },
              { name: 'Weather delay', n: 8, pct: 57 },
              { name: 'Lawn treatment', n: 6, pct: 43 },
              { name: 'Service credit', n: 4, pct: 29 },
              { name: 'HOA board', n: 3, pct: 21 },
            ].map(t => (
              <div key={t.name} className="topicbar">
                <span className="name">{t.name}</span>
                <span className="bar"><i style={{ width: t.pct + '%' }}></i></span>
                <span className="n">{t.n}</span>
              </div>
            ))}
          </div>

          <div className="card">
            <h4>Action Items</h4>
            <ul className="actions" style={{ listStyle: 'none', padding: 0, margin: 0 }}>
              <li>
                <span className="cb"></span>
                <div>
                  Dispatch crew to 2140 Ridgeview Pkwy, tomorrow 8–10 AM
                  <div className="who">Auto-assigned · J. Mercer · Due tomorrow</div>
                </div>
              </li>
              <li>
                <span className="cb"></span>
                <div>
                  Apply 15% service credit to next invoice
                  <div className="who">Billing queue · Due EOD</div>
                </div>
              </li>
              <li>
                <span className="cb"></span>
                <div>
                  Confirm text notification 30 min before arrival
                  <div className="who">Crew lead system · Automated</div>
                </div>
              </li>
            </ul>
          </div>

          <div className="card">
            <h4>Call Metadata</h4>
            <div className="kv"><span className="k">Call ID</span><span className="v mono">QSC-248193</span></div>
            <div className="kv"><span className="k">Campaign</span><span className="v">Inbound · Service</span></div>
            <div className="kv"><span className="k">Direction</span><span className="v">Inbound</span></div>
            <div className="kv"><span className="k">Queue wait</span><span className="v mono">0:42</span></div>
            <div className="kv"><span className="k">Transfer count</span><span className="v">0</span></div>
            <div className="kv"><span className="k">CSAT (post-call)</span><span className="v" style={{ color: 'var(--pos)' }}>4.6 / 5</span></div>
            <div className="kv"><span className="k">Recording</span><span className="v mono">wav · 14.1 MB</span></div>
          </div>

        </div>
      </div>
    </>
  );
}

window.Detail = Detail;
