// Library (call list) page
const { useState: useStateLib, useMemo: useMemoLib } = React;

function Library({ onOpenCall }) {
  const { CALLS, AGENTS } = window.VI_DATA;
  const [sentFilter, setSentFilter] = useStateLib(['pos','neu','neg']);
  const [flaggedOnly, setFlaggedOnly] = useStateLib(false);

  const rows = useMemoLib(() => CALLS.filter(c =>
    sentFilter.includes(c.sentiment) && (!flaggedOnly || c.flagged)
  ), [sentFilter, flaggedOnly]);

  const toggleSent = (s) => setSentFilter(f => f.includes(s) ? f.filter(x => x !== s) : [...f, s]);

  const agentById = (id) => AGENTS.find(a => a.id === id);

  return (
    <>
      <div className="page-head">
        <div>
          <h1>Call Library</h1>
          <div className="sub">
            Browsing <span className="mono">3,281 calls</span> · Last 30 days · All teams
          </div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="download" /> Export CSV</button>
          <button className="btn"><Icon name="share" /> Share view</button>
          <button className="btn primary"><Icon name="plus" /> New saved view</button>
        </div>
      </div>

      <div className="lib-layout">
        {/* Filters */}
        <aside className="filters">
          <div className="filter-group">
            <div className="label"><span>Date range</span><span className="clear">Reset</span></div>
            <div className="chip-row">
              <span className="chip on">Last 30d</span>
              <span className="chip">7d</span>
              <span className="chip">QTD</span>
              <span className="chip">Custom…</span>
            </div>
          </div>

          <div className="filter-group">
            <div className="label"><span>Sentiment</span></div>
            {[
              { k: 'pos', label: 'Positive', n: 2104 },
              { k: 'neu', label: 'Neutral',  n:  843 },
              { k: 'neg', label: 'Negative', n:  334 },
            ].map(o => (
              <div key={o.k}
                   className={'chk ' + (sentFilter.includes(o.k) ? 'on' : '')}
                   onClick={() => toggleSent(o.k)}>
                <div className="left">
                  <div className="box"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5 9-11"/></svg></div>
                  <span>{o.label}</span>
                </div>
                <span className="count">{o.n.toLocaleString()}</span>
              </div>
            ))}
          </div>

          <div className="filter-group">
            <div className="label"><span>Call duration</span></div>
            <div className="range"><span>0:00</span><span>45:00</span></div>
            <div className="range-bar"></div>
            <div className="range" style={{ color: 'var(--ink)' }}><span>3:12</span><span>18:40</span></div>
          </div>

          <div className="filter-group">
            <div className="label"><span>Team</span></div>
            {['Install Support','Billing','Retention','Tier 2 Escalation'].map((t, i) => (
              <div key={t} className={'chk ' + (i < 3 ? 'on' : '')}>
                <div className="left">
                  <div className="box"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><path d="M5 12l5 5 9-11"/></svg></div>
                  <span>{t}</span>
                </div>
                <span className="count">{[1284, 904, 612, 481][i]}</span>
              </div>
            ))}
          </div>

          <div className="filter-group">
            <div className="label"><span>Intent</span></div>
            <div className="chip-row">
              {['Scheduling','Billing','Cancellation','New install','Complaint','Follow-up'].map((t, i) => (
                <span key={t} className={'chip sm ' + (i % 2 === 0 ? 'on' : '')}>{t}</span>
              ))}
            </div>
          </div>

          <div className="filter-group">
            <div className="label"><span>Flags</span></div>
            <div className="chk" onClick={() => setFlaggedOnly(v => !v)}>
              <div className="left">
                <div className={'box ' + (flaggedOnly ? '' : '')} style={{ background: flaggedOnly ? 'var(--blue)' : 'var(--panel)', borderColor: flaggedOnly ? 'var(--blue)' : 'var(--hair-2)' }}>
                  {flaggedOnly && <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3" style={{ width: 10, height: 10, display: 'block' }}><path d="M5 12l5 5 9-11"/></svg>}
                </div>
                <span>Flagged for QA review</span>
              </div>
              <span className="count">147</span>
            </div>
            <div className="chk">
              <div className="left"><div className="box"></div><span>Contains PII</span></div>
              <span className="count">28</span>
            </div>
            <div className="chk">
              <div className="left"><div className="box"></div><span>Escalated</span></div>
              <span className="count">64</span>
            </div>
          </div>
        </aside>

        {/* Results */}
        <section className="results">
          <div className="results-head">
            <div className="count"><b>{rows.length.toString().padStart(3, '0')}</b> of 3,281 · sorted by <b>most recent</b></div>
            <div className="row" style={{ gap: 10 }}>
              <button className="btn"><Icon name="filter" /> More filters</button>
              <button className="btn">Sort: Most recent <Icon name="chevdown" /></button>
            </div>
          </div>

          <table className="tbl">
            <thead>
              <tr>
                <th style={{ width: 110 }}>ID</th>
                <th>Customer</th>
                <th>Agent</th>
                <th>When</th>
                <th>Duration</th>
                <th>Waveform</th>
                <th>Sentiment</th>
                <th>Intent</th>
                <th style={{ textAlign: 'right' }}>QA score</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((c, i) => {
                const ag = agentById(c.agent);
                return (
                  <tr key={c.id} onClick={() => onOpenCall(c.id)}>
                    <td className="id">{c.id}</td>
                    <td>
                      <div style={{ fontWeight: 500 }}>{c.customer}</div>
                      <div style={{ fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>
                        {c.topics.slice(0, 2).join(' · ')}
                      </div>
                    </td>
                    <td>
                      <div className="agent">
                        <div className="av" style={{ background: ag.avatar }}>{ag.id}</div>
                        <div>
                          <div style={{ fontWeight: 500 }}>{ag.name}</div>
                          <div style={{ fontSize: 11, color: 'var(--muted)' }}>{ag.team}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ color: 'var(--ink-2)' }}>{c.when}</td>
                    <td className="dur">{c.dur}</td>
                    <td>
                      <div className="mini-wave">
                        {Array.from({ length: 32 }).map((_, j) => {
                          const r = ((c.id.charCodeAt(8) + j * 7 + i * 3) % 100) / 100;
                          return <i key={j} style={{ height: 4 + r * 16 + 'px' }} />;
                        })}
                      </div>
                    </td>
                    <td>
                      <span className={'pill ' + c.sentiment}>
                        {c.sentiment === 'pos' ? 'Positive' : c.sentiment === 'neu' ? 'Neutral' : 'Negative'}
                      </span>
                    </td>
                    <td>
                      <div>{c.intent}</div>
                    </td>
                    <td className="score" style={{ textAlign: 'right', color: c.score >= 80 ? 'var(--pos)' : c.score >= 65 ? 'var(--ink)' : 'var(--neg)' }}>
                      {c.score}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 18, fontSize: 12, color: 'var(--muted)' }}>
            <div>Showing 1–{rows.length} of 3,281</div>
            <div className="row" style={{ gap: 6 }}>
              <button className="btn" disabled style={{ opacity: .5 }}>Previous</button>
              <button className="btn">Next</button>
            </div>
          </div>
        </section>
      </div>
    </>
  );
}

window.Library = Library;
