// Live admin portal views for the Phone systems page, recreated from ui_kits/admin-portal (Riverside Dental demo domain).
// Each view renders at a fixed desktop width and scales down to fit its box, like a screenshot that stays sharp.
const PS_TABS = [['House', 'Home'], ['Users', 'Users'], ['Mic', 'Conf'], ['Phone', 'Auto Att'], ['ClipboardList', 'Queues'], ['Clock', 'Time'], ['Music', 'MoH'], ['Package', 'Inventory'], ['ChartColumn', 'Call Hist']];
const PS_HOURS = [0, 0, 0, 0, 0, 1, 3, 6, 11, 14, 18, 16, 12, 15, 17, 13, 9, 6, 3, 1, 0, 0, 0, 0];
const PS_DAYS = [12, 15, 18, 14, 16, 4, 2, 13, 17, 18, 15, 14, 3, 1, 14, 16, 17, 15, 12, 5, 2, 15, 18, 16, 14, 13, 4, 2, 16, 17];
const PS_CALLS = [['(469) 555-0182', 'Main line', 'AI receptionist'], ['(214) 555-0147', 'Main line', 'Front desk, ext 101'], ['(972) 555-0193', 'Billing', 'Hunt group: Billing']];

// Plays while at least a third of the element is on screen and the tab is visible
function useOnScreen(ref) {
  const [on, setOn] = React.useState(false);
  React.useEffect(() => {
    let seen = false; const upd = () => setOn(seen && !document.hidden);
    const io = new IntersectionObserver(([e]) => { seen = e.isIntersecting; upd(); }, { threshold: 0.3 });
    io.observe(ref.current); document.addEventListener('visibilitychange', upd);
    return () => { io.disconnect(); document.removeEventListener('visibilitychange', upd); };
  }, []);
  return on;
}

function PortalFrame({ label, width = 1040, children }) {
  const outer = React.useRef(null), inner = React.useRef(null); const [box, setBox] = React.useState({ s: 1, h: 0 });
  React.useEffect(() => {
    const fit = () => { if (!outer.current || !inner.current) return; const s = outer.current.clientWidth / width; setBox({ s, h: inner.current.offsetHeight * s }); };
    const ro = new ResizeObserver(fit); ro.observe(outer.current); ro.observe(inner.current); fit(); return () => ro.disconnect();
  }, [width]);
  return <figure className="ps" aria-label={label}>
    <div className="ps-chrome" aria-hidden="true"><span /><span /><span /><em><DS.Icon name="Lock" size={11} /> OneCloud admin portal</em></div>
    <div className="ps-view" ref={outer} style={{ height: box.h || undefined }}><div className="ps-scale" ref={inner} style={{ width, transform: `scale(${box.s})` }}>{children}</div></div>
  </figure>;
}

const PsPanel = ({ title, action, children }) => <div className="ps-panel"><div className="ps-panel-h">{title}{action}</div><div className="ps-panel-b">{children}</div></div>;
const PsKV = ({ rows }) => <div className="ps-kv">{rows.map(([n, l]) => <div key={l}><span>{l}</span><b className="num">{n}</b></div>)}</div>;
function PsBars({ data, h = 120, labels, grown, now }) {
  const max = Math.max(...data);
  return <div><div className="ps-bars" style={{ height: h }}>{data.map((v, i) => <div key={i} className={'ps-bar' + (v === max ? ' peak' : '') + (i === now ? ' now' : '')} style={{ height: (v / max) * h, transform: grown ? 'none' : 'scaleY(0)', transitionDelay: grown ? i * 18 + 'ms' : '0ms' }} />)}</div>
    {labels && <div className="ps-bar-l">{labels.map((l, i) => <div key={i}>{l}</div>)}</div>}</div>;
}
function PsChrome({ tab, children }) {
  return <div className="ps-app">
    <div className="ps-banner"><span>You are viewing the <b>Riverside Dental</b> domain.</span><span className="ps-link">Edit Domain Configs</span></div>
    <div className="ps-top"><span className="ps-logo">One<span>Cloud</span> <i>Networks</i></span><span className="ps-menu">Help <em>|</em> Apps ▾ <em>|</em> Admin ▾</span></div>
    <div className="ps-tabs">{PS_TABS.map(([ic, l]) => <span key={l} className={l === tab ? 'on' : ''}><DS.Icon name={ic} size={20} />{l}</span>)}</div>
    <div className="ps-main">{children}</div>
  </div>;
}

// Home: a call arrives in Current Active Calls, its timer ticks, then it ends and Calls Today goes up
function PortalHome() {
  const ref = React.useRef(null); const on = useOnScreen(ref); const [grown, setGrown] = React.useState(false);
  const [k, setK] = React.useState(0), [call, setCall] = React.useState(null), [secs, setSecs] = React.useState(0), [today, setToday] = React.useState(47), [mins, setMins] = React.useState(184);
  React.useEffect(() => { if (on) setGrown(true); }, [on]);
  React.useEffect(() => {
    if (!on) return;
    const start = setTimeout(() => { setCall(PS_CALLS[k % PS_CALLS.length]); setSecs(0); }, 1400);
    const tick = setInterval(() => setSecs(s => s + 1), 1000);
    const end = setTimeout(() => { setCall(null); setToday(t => t + 1); setMins(m => m + 2); }, 9400);
    const next = setTimeout(() => setK(x => x + 1), 11500);
    return () => { [start, end, next].forEach(clearTimeout); clearInterval(tick); };
  }, [on, k]);
  const dur = Math.max(0, secs - 1);
  return <div ref={ref}><PsChrome tab="Home">
    <div className="ps-title">Home <span className="ps-icbtn"><DS.Icon name="RefreshCw" size={14} /></span></div>
    <PsPanel title="Current Active Calls"><table className="ps-table"><thead><tr>{['From', 'Dialed', 'To', 'Duration'].map(h => <th key={h}>{h}</th>)}</tr></thead>
      <tbody>{call ? <tr key={k} className="ps-row-in"><td className="num">{call[0]}</td><td>{call[1]}</td><td>{call[2]}</td><td className="num"><span className="ps-live" />{String(Math.floor(dur / 60)).padStart(2, '0')}:{String(dur % 60).padStart(2, '0')}</td></tr>
        : <tr><td colSpan={4} className="ps-empty">There are no active calls.</td></tr>}</tbody></table></PsPanel>
    <PsPanel title="Peak Active Calls by Hour for All Calls"><PsBars data={PS_HOURS} grown={grown} now={10} labels={PS_HOURS.map((_, i) => i % 3 === 0 ? i + ':00' : '')} /></PsPanel>
    <div className="ps-two">
      <PsPanel title="Users and Applications"><PsKV rows={[['52', 'Users'], ['49', 'Registered Devices'], ['93', 'Total Devices'], ['3', 'Auto Attendants'], ['83', 'Phone Numbers']]} /></PsPanel>
      <PsPanel title="Usage Statistics"><PsKV rows={[[call ? '1' : '0', 'Active Calls'], [String(today), 'Calls Today'], [String(mins), 'Total Min Today'], ['4', 'Avg Talk Time']]} /></PsPanel>
    </div>
  </PsChrome></div>;
}

// Domain Statistics: numbers count up and the month's bars grow in; the By Day / By Hour switch works
function PortalStats() {
  const ref = React.useRef(null); const on = useOnScreen(ref); const [grown, setGrown] = React.useState(false), [t, setT] = React.useState('day');
  React.useEffect(() => { if (on) setGrown(true); }, [on]);
  const data = t === 'day' ? PS_DAYS : PS_HOURS;
  return <div ref={ref}><PsChrome tab="Call Hist">
    <div className="ps-title ps-title-row">Domain Statistics<span className="ps-actions"><span className="ps-btn">CDR Export</span><span className="ps-btn">Hunt Groups</span></span></div>
    <div className="ps-kpis">{[['18', 'Peak Active Calls', '↑ by hour, day, minute'], ['4,832', 'Total Minutes', '↑ 15% this month'], ['24', 'Subscribers', 'Active extensions'], ['3', 'Active Queues', 'ACD configured']].map(([n, l, s]) => <div key={l} className="ps-kpi"><div className="ps-kpi-l">{l}</div><div className="ps-kpi-n num">{grown ? <CountUp value={n} duration={1100} /> : '0'}</div><div className={'ps-kpi-s' + (s.startsWith('↑') ? ' up' : '')}>{s}</div></div>)}</div>
    <PsPanel title="Peak Active Calls, This Month" action={<span className="ps-seg" role="group" aria-label="Chart range">{[['day', 'By Day'], ['hour', 'By Hour']].map(([v, l]) => <button key={v} type="button" aria-pressed={t === v} onClick={() => setT(v)}>{l}</button>)}</span>}>
      <PsBars key={t} data={data} h={170} grown={grown} labels={data.map((_, i) => t === 'day' ? (i % 5 === 0 ? i + 1 : '') : (i % 3 === 0 ? i + ':00' : ''))} />
    </PsPanel>
  </PsChrome></div>;
}
Object.assign(window, { PortalFrame, PortalHome, PortalStats });
