// shell.jsx — App shell: Sidebar, Topbar, Tabs, Date Range, Download menu, AI Banner

const { useState, useRef, useEffect } = React;

function fmtShort(d) {
  const M = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  return `${d.getUTCDate()} ${M[d.getUTCMonth()]} ${String(d.getUTCFullYear()).slice(-2)}`;
}

function Sidebar({ active, onChange }) {
  const items = [
    { id: 'overview', label: 'Overview', icon: 'Home' },
    { id: 'meta', label: 'Meta Ads', icon: 'Layers' },
    { id: 'google', label: 'Google Ads', icon: 'Google' },
    { id: 'seo', label: 'SEO', icon: 'Search' },
    { id: 'funnel', label: 'Website Funnel', icon: 'Funnel' },
  ];
  return (
    <aside className="sb">
      <div className="sb-brand">
        <div className="sb-logo">س</div>
        <div>
          <div className="sb-name">Silsal</div>
          <div className="sb-sub">BI Cockpit</div>
        </div>
      </div>
      <div className="sb-section">Reports</div>
      {items.map(it => {
        const I = Icons[it.icon];
        return (
          <div key={it.id} className={`sb-item ${active === it.id ? 'active' : ''}`} onClick={() => onChange(it.id)}>
            <span className="sb-icon"><I size={16}/></span>
            {it.label}
          </div>
        );
      })}
      <div className="sb-foot">
        <div className="sb-avatar">RS</div>
        <Icons.Chevron size={14}/>
      </div>
    </aside>
  );
}

function DateRange({ range, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  const opts = [
    { id: '7d', label: 'Last 7 days' },
    { id: '30d', label: 'Last 30 days' },
    { id: '90d', label: 'Last 90 days' },
    { id: '12m', label: 'Last 12 months' },
    { id: 'ytd', label: 'Year to date' },
  ];
  const cur = opts.find(o => o.id === range);
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <div className="btn" onClick={() => setOpen(!open)}>
        <Icons.Calendar size={14}/>
        {cur.label}
        <Icons.Chevron size={13}/>
      </div>
      {open && (
        <div className="pop">
          <div className="pop-label">Quick ranges</div>
          {opts.map(o => (
            <div key={o.id} className={`pop-item ${o.id === range ? 'active' : ''}`} onClick={() => { onChange(o.id); setOpen(false); }}>
              {o.label}
              {o.id === range && <Icons.Check size={14}/>}
            </div>
          ))}
          <div className="pop-divider"/>
          <div className="pop-item">Custom range… <Icons.ChevronRight size={13}/></div>
        </div>
      )}
    </div>
  );
}

function CountryFilter({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);
  const cs = SilsalData.COUNTRIES;
  const label = value === 'all' ? 'All countries' : cs.find(c => c.code === value).name;
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <div className="btn" onClick={() => setOpen(!open)}>
        <Icons.Globe size={14}/>
        {label}
        <Icons.Chevron size={13}/>
      </div>
      {open && (
        <div className="pop" style={{ minWidth: 180 }}>
          <div className={`pop-item ${value === 'all' ? 'active' : ''}`} onClick={() => { onChange('all'); setOpen(false); }}>
            <span className="row"><Icons.Globe size={13}/> All countries</span>
            {value === 'all' && <Icons.Check size={14}/>}
          </div>
          <div className="pop-divider"/>
          {cs.map(c => (
            <div key={c.code} className={`pop-item ${value === c.code ? 'active' : ''}`} onClick={() => { onChange(c.code); setOpen(false); }}>
              <span className="row"><span style={{ fontSize: 14 }}>{c.flag}</span> {c.name}</span>
              {value === c.code && <Icons.Check size={14}/>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function GranularityToggle({ value, onChange }) {
  const opts = [
    { id: 'daily', label: 'Daily' },
    { id: 'weekly', label: 'Weekly' },
    { id: 'monthly', label: 'Monthly' },
    { id: 'quarterly', label: 'Quarterly' },
  ];
  return (
    <div className="seg">
      {opts.map(o => (
        <div key={o.id} className={`seg-item ${value === o.id ? 'active' : ''}`} onClick={() => onChange(o.id)}>{o.label}</div>
      ))}
    </div>
  );
}

function DownloadMenu() {
  const [open, setOpen] = useState(false);
  const [format, setFormat] = useState('pdf');
  const [scope, setScope] = useState('all');
  const [exporting, setExporting] = useState(false);
  const [done, setDone] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  const run = () => {
    setExporting(true); setDone(false);
    setTimeout(() => { setExporting(false); setDone(true); setTimeout(() => { setDone(false); setOpen(false); }, 1200); }, 1500);
  };

  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <div className="btn btn-primary" onClick={() => setOpen(!open)}>
        <Icons.Download size={14}/>
        Export
        <Icons.Chevron size={13}/>
      </div>
      {open && (
        <div className="pop" style={{ minWidth: 280, padding: 14 }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Export dashboard</div>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 6 }}>Format</div>
          <div className="seg" style={{ width: '100%', marginBottom: 12 }}>
            <div className={`seg-item ${format === 'pdf' ? 'active' : ''}`} style={{ flex: 1, justifyContent: 'center' }} onClick={() => setFormat('pdf')}>
              <Icons.Pdf size={13}/>&nbsp;PDF
            </div>
            <div className={`seg-item ${format === 'xlsx' ? 'active' : ''}`} style={{ flex: 1, justifyContent: 'center' }} onClick={() => setFormat('xlsx')}>
              <Icons.Excel size={13}/>&nbsp;Excel
            </div>
            <div className={`seg-item ${format === 'both' ? 'active' : ''}`} style={{ flex: 1, justifyContent: 'center' }} onClick={() => setFormat('both')}>
              Both
            </div>
          </div>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--ink-4)', marginBottom: 6 }}>Scope</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 12 }}>
            {[
              { id: 'all', label: 'Entire dashboard (all 5 tabs)' },
              { id: 'current', label: 'Current tab only' },
              { id: 'kpis', label: 'KPIs + AI insights only' },
            ].map(o => (
              <label key={o.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 8px', borderRadius: 7, cursor: 'default', background: scope === o.id ? 'var(--accent-soft)' : 'transparent' }}>
                <input type="radio" checked={scope === o.id} onChange={() => setScope(o.id)} style={{ accentColor: 'var(--accent)' }}/>
                <span style={{ fontSize: 12.5 }}>{o.label}</span>
              </label>
            ))}
          </div>
          <div className="btn btn-primary" style={{ width: '100%', justifyContent: 'center' }} onClick={run}>
            {exporting ? <><span className="ai-pulse"/> &nbsp;Generating…</> : done ? <><Icons.Check size={14}/> &nbsp;Ready — downloading</> : <><Icons.Download size={14}/> &nbsp;Generate {format === 'both' ? 'PDF + XLSX' : format.toUpperCase()}</>}
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-4)', marginTop: 8, textAlign: 'center' }}>
            Includes data range, comparison, AI commentary
          </div>
        </div>
      )}
    </div>
  );
}

function AIBanner({ insights, accent = 'var(--accent)' }) {
  const [expanded, setExpanded] = useState(false);
  const main = insights[0];
  return (
    <div className="ai-banner">
      <div className="ai-icon"><Icons.Sparkle size={16}/></div>
      <div className="ai-content">
        <div className="ai-title row"><span>AI Insight</span><span className="ai-pulse"/></div>
        <div className="ai-text" dangerouslySetInnerHTML={{ __html: main }}/>
        {expanded && insights.slice(1).map((t, i) => (
          <div key={i} className="ai-text" style={{ marginTop: 8, paddingTop: 8, borderTop: '1px solid rgba(91,91,240,0.12)' }} dangerouslySetInnerHTML={{ __html: t }}/>
        ))}
      </div>
      <div className="ai-actions">
        {insights.length > 1 && (
          <div className="btn btn-ghost" onClick={() => setExpanded(!expanded)} style={{ color: 'var(--accent)' }}>
            {expanded ? 'Collapse' : `+${insights.length - 1} more`}
            {expanded ? <Icons.ChevronUp size={13}/> : <Icons.Chevron size={13}/>}
          </div>
        )}
        <div className="btn btn-ghost btn-icon" title="Dismiss"><Icons.Close size={14}/></div>
      </div>
    </div>
  );
}

function Topbar({ tab, range, setRange, country, setCountry, granularity, setGranularity }) {
  const TITLES = {
    overview: { t: 'Overview', s: 'Cross-channel performance across UAE, KSA, Qatar' },
    meta:     { t: 'Meta Ads',  s: 'Facebook & Instagram campaigns · Advantage+ included' },
    google:   { t: 'Google Ads',s: 'Search · Performance Max · Shopping · YouTube' },
    seo:      { t: 'SEO',       s: 'Organic search performance & keyword landscape' },
    funnel:   { t: 'Website Funnel', s: 'Sessions → Add to cart → Purchase journey' },
  };
  const cur = TITLES[tab];
  return (
    <>
      <div className="tb">
        <div className="tb-left">
          <div>
            <div className="tb-crumb">Silsal · Dashboards · live data {SilsalData.rangeBounds && (() => { const b = SilsalData.rangeBounds(range); return `${fmtShort(b.start)}–${fmtShort(b.end)}`; })()}</div>
            <div className="tb-title">{cur.t}</div>
          </div>
        </div>
        <div className="tb-right">
          <div className="btn btn-ghost btn-icon" title="Refresh"><Icons.Refresh size={14}/></div>
          <CountryFilter value={country} onChange={setCountry}/>
          <DateRange range={range} onChange={setRange}/>
          <DownloadMenu/>
        </div>
      </div>
    </>
  );
}

function TabBar({ tab, onChange, granularity, setGranularity, compare, setCompare }) {
  return (
    <div className="tabs">
      <div className="spacer"/>
      <div className="row" style={{ paddingRight: 0, gap: 8 }}>
        <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 500 }}>Compare</span>
        <div className="seg">
          <div className={`seg-item ${compare === 'prev' ? 'active' : ''}`} onClick={() => setCompare('prev')}>Previous</div>
          <div className={`seg-item ${compare === 'yoy' ? 'active' : ''}`} onClick={() => setCompare('yoy')}>YoY</div>
          <div className={`seg-item ${compare === 'none' ? 'active' : ''}`} onClick={() => setCompare('none')}>Off</div>
        </div>
        <span style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 500, marginLeft: 8 }}>View</span>
        <GranularityToggle value={granularity} onChange={setGranularity}/>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, TabBar, AIBanner, DateRange, CountryFilter, GranularityToggle, DownloadMenu });
