/* global React, Icon, StatusPill, Avatar, fmtAED */
const { useState } = React;

/* ============================================================
   DOCUMENTS LIST + BUILDER + PUBLIC VIEWER
   ============================================================ */

function Documents({ goto }) {
  const [filter, setFilter] = useState('all');
  let docs = window.DOCUMENTS;
  if (filter !== 'all') docs = docs.filter(d => d.type === filter);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Sales</div>
          <h1 className="page-title">Documents</h1>
          <div className="page-subtitle">Proposals, pitch decks, recap decks</div>
        </div>
        <div className="page-header-right">
          <button className="btn btn-primary" onClick={() => goto('document-builder', 'doc1')}><Icon name="plus" size={12} /> New document</button>
        </div>
      </div>
      <div style={{ padding: '10px 28px', borderBottom: '1px solid var(--divider)', display: 'flex', gap: 6 }}>
        {['all','proposal','pitch','recap'].map(f => (
          <button key={f} onClick={() => setFilter(f)} className="btn btn-sm" style={{
            background: filter === f ? 'var(--raised)' : 'transparent',
            borderColor: filter === f ? 'var(--divider-strong)' : 'var(--divider)',
            textTransform: 'capitalize',
          }}>{f}</button>
        ))}
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 14 }}>
          {docs.map(d => (
            <div key={d.id} className="card" style={{ padding: 0, cursor: 'pointer' }} onClick={() => goto('document-builder', d.id)}>
              <div style={{ aspectRatio: '4/3', background: d.theme === 'linea-light' ? '#f4f4f4' : '#0a0a0a', display: 'flex', alignItems: 'center', justifyContent: 'center', borderBottom: '1px solid var(--divider)', position: 'relative' }}>
                <div style={{ textAlign: 'center', padding: 20 }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 22, color: d.theme === 'linea-light' ? '#0e0e0e' : '#f5f5f5', letterSpacing: '-0.02em', lineHeight: 1 }}>
                    {d.title.split('·')[1] || d.title}
                  </div>
                  <div style={{ width: 24, height: 2, background: '#22c55e', margin: '10px auto 0' }}></div>
                </div>
                <div style={{ position: 'absolute', top: 8, left: 8 }}>
                  <span className="chip" style={{ textTransform: 'capitalize' }}>{d.type}</span>
                </div>
              </div>
              <div style={{ padding: 12 }}>
                <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 4, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{d.title}</div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 10 }}>
                  <span style={{ color: 'var(--text-dim)' }}>{d.contact} · {d.slides} slides</span>
                  <StatusPill status={d.status} />
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function DocumentBuilder({ docId, goto }) {
  const doc = window.DOCUMENTS.find(d => d.id === docId) || window.DOCUMENTS[0];
  const [theme, setTheme] = useState(doc.theme);
  const [activeSlide, setActiveSlide] = useState(0);
  const [viewer, setViewer] = useState(false);

  const slides = [
    { kind: 'cover', title: doc.title, sub: 'Linea Group · Q2 2026' },
    { kind: 'agenda', items: ['Where you are now', 'What we see', 'How we fix it', 'Investment + timeline', 'Next step'] },
    { kind: 'problem', headline: 'Your funnel leaks at 3 critical points.', body: 'Cold acquisition is fine. Conversion below 1.4%. Email follow-up at 0.' },
    { kind: 'kpi', headline: 'What we delivered for clients like you.' },
    { kind: 'pricing', headline: 'Investment.' },
    { kind: 'cta', headline: 'Ready to start?' },
  ];

  const current = slides[activeSlide];

  if (viewer) {
    return <PublicViewer slides={slides} theme={theme} onClose={() => setViewer(false)} />;
  }

  const isDark = theme === 'linea-dark';

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr 280px', height: '100%', overflow: 'hidden' }}>
      {/* Slide thumbnails */}
      <div style={{ borderRight: '1px solid var(--divider)', overflowY: 'auto', padding: 12 }}>
        <button className="btn btn-ghost btn-sm" style={{ padding: '4px 6px', marginBottom: 12 }} onClick={() => goto('documents')}>
          <Icon name="chevLeft" size={12} /> Documents
        </button>
        <div className="label" style={{ marginBottom: 8, padding: '0 4px' }}>Slides · {slides.length}</div>
        {slides.map((s, i) => (
          <div key={i} draggable onClick={() => setActiveSlide(i)}
            style={{
              padding: 6, marginBottom: 6, cursor: 'pointer',
              border: '1px solid', borderColor: i === activeSlide ? 'var(--accent)' : 'var(--divider)',
              background: i === activeSlide ? 'var(--raised)' : 'transparent',
              display: 'flex', gap: 6, alignItems: 'center',
            }}>
            <div style={{ width: 14, fontSize: 9, color: 'var(--text-dim)', flexShrink: 0 }} className="mono">{i+1}</div>
            <div style={{ flex: 1, aspectRatio: '16/9', background: isDark ? '#0a0a0a' : '#f4f4f4', border: '1px solid var(--divider)', overflow: 'hidden', position: 'relative' }}>
              <div style={{ position: 'absolute', inset: 0, padding: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 6, color: isDark ? '#f5f5f5' : '#0e0e0e', fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 700, textAlign: 'center', overflow: 'hidden' }}>
                {s.headline || s.title || s.kind}
              </div>
            </div>
          </div>
        ))}
        <button className="btn btn-sm" style={{ width: '100%', justifyContent: 'center', marginTop: 4 }}><Icon name="plus" size={11} /> Add</button>
      </div>

      {/* Canvas */}
      <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', background: 'var(--bg)' }}>
        <div style={{ padding: '10px 20px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>Slide {activeSlide + 1} / {slides.length}</span>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button className="btn btn-sm" onClick={() => setViewer(true)}><Icon name="eye" size={11} /> Present</button>
            <button className="btn btn-sm"><Icon name="link" size={11} /> Share link</button>
            <button className="btn btn-primary btn-sm"><Icon name="send" size={11} /> Send to {doc.contact.split(' ')[0]}</button>
          </div>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: 32, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: '100%', maxWidth: 920, aspectRatio: '16/9', boxShadow: '0 0 0 1px var(--divider)' }}>
            <SlideRender slide={current} theme={theme} />
          </div>
        </div>
      </div>

      {/* Properties + theme picker */}
      <div style={{ borderLeft: '1px solid var(--divider)', overflowY: 'auto', padding: 16 }}>
        <div className="label" style={{ marginBottom: 10 }}>Theme</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 18 }}>
          {[
            { id: 'linea-dark', label: 'Linea Dark', bg: '#0a0a0a', text: '#f5f5f5' },
            { id: 'linea-light', label: 'Linea Light', bg: '#f4f4f4', text: '#0e0e0e' },
          ].map(t => (
            <div key={t.id} onClick={() => setTheme(t.id)} style={{
              padding: 10, border: '1px solid', borderColor: theme === t.id ? 'var(--accent)' : 'var(--divider)',
              cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
              background: theme === t.id ? 'var(--raised)' : 'transparent',
            }}>
              <div style={{ width: 28, height: 20, background: t.bg, border: '1px solid var(--divider)', position: 'relative' }}>
                <div style={{ position: 'absolute', left: 3, top: 3, width: 10, height: 2, background: t.text }}></div>
                <div style={{ position: 'absolute', left: 3, top: 7, width: 16, height: 2, background: '#22c55e' }}></div>
              </div>
              <span style={{ fontSize: 12, fontWeight: 500 }}>{t.label}</span>
            </div>
          ))}
          <div style={{ padding: 10, border: '1px dashed var(--divider)', fontSize: 11, color: 'var(--text-dim)', textAlign: 'center' }}>
            + Client-Brand theme
          </div>
        </div>

        <div className="label" style={{ marginBottom: 10 }}>Slide · {current.kind}</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div>
            <div className="label" style={{ marginBottom: 4 }}>Type</div>
            <select className="input">
              {['Cover','Agenda','Problem','Solution','KPI Grid','Before/After','Quote','Pricing','Timeline','Terms','CTA','Contact'].map(t => <option key={t}>{t}</option>)}
            </select>
          </div>
          <div>
            <div className="label" style={{ marginBottom: 4 }}>Headline</div>
            <input className="input" defaultValue={current.headline || current.title} />
          </div>
          {current.body && (
            <div>
              <div className="label" style={{ marginBottom: 4 }}>Body</div>
              <textarea className="textarea" defaultValue={current.body} />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function SlideRender({ slide, theme }) {
  const isDark = theme === 'linea-dark';
  const bg = isDark ? '#0a0a0a' : '#f4f4f4';
  const fg = isDark ? '#f5f5f5' : '#0e0e0e';
  const dim = isDark ? '#a3a3a3' : '#525252';
  const accent = '#22c55e';

  const fontDisplay = { fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.05, color: fg };
  const labelStyle = { fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.1em', color: dim };

  if (slide.kind === 'cover') {
    return (
      <div style={{ width: '100%', height: '100%', background: bg, padding: '8% 8%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ width: 18, height: 18, background: accent }}></div>
          <span style={{ ...labelStyle, color: fg, opacity: 0.6 }}>Linea Group</span>
        </div>
        <div>
          <div style={{ width: 60, height: 3, background: accent, marginBottom: 24 }}></div>
          <h1 style={{ ...fontDisplay, fontSize: 60, margin: 0 }}>{slide.title}</h1>
          <div style={{ ...labelStyle, marginTop: 24 }}>{slide.sub}</div>
        </div>
      </div>
    );
  }
  if (slide.kind === 'agenda') {
    return (
      <div style={{ width: '100%', height: '100%', background: bg, padding: '8% 8%', display: 'flex', flexDirection: 'column' }}>
        <div style={labelStyle}>Agenda</div>
        <div style={{ width: 40, height: 2, background: accent, margin: '14px 0 28px' }}></div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {slide.items.map((it, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'baseline', gap: 18 }}>
              <span className="mono" style={{ color: dim, fontSize: 14, width: 30 }}>0{i+1}</span>
              <span style={{ ...fontDisplay, fontSize: 28 }}>{it}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (slide.kind === 'problem') {
    return (
      <div style={{ width: '100%', height: '100%', background: bg, padding: '8% 8%', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={labelStyle}>The Problem</div>
        <h1 style={{ ...fontDisplay, fontSize: 56, margin: '14px 0 24px', maxWidth: '85%' }}>{slide.headline}</h1>
        <p style={{ color: dim, fontSize: 18, maxWidth: '70%', lineHeight: 1.5, margin: 0 }}>{slide.body}</p>
      </div>
    );
  }
  if (slide.kind === 'kpi') {
    return (
      <div style={{ width: '100%', height: '100%', background: bg, padding: '8% 8%', display: 'flex', flexDirection: 'column' }}>
        <div style={labelStyle}>What we delivered</div>
        <h1 style={{ ...fontDisplay, fontSize: 44, margin: '14px 0 36px', maxWidth: '85%' }}>{slide.headline}</h1>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28, flex: 1 }}>
          {[
            { v: '4.2x', l: 'ROAS · 90 days' },
            { v: '+312%', l: 'Email revenue' },
            { v: '−38%', l: 'CAC reduction' },
          ].map((k, i) => (
            <div key={i} style={{ borderTop: '1px solid ' + (isDark ? '#262626' : '#d4d4d4'), paddingTop: 18 }}>
              <div className="mono" style={{ fontSize: 56, color: accent, lineHeight: 1, fontWeight: 500 }}>{k.v}</div>
              <div style={{ ...labelStyle, marginTop: 12 }}>{k.l}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (slide.kind === 'pricing') {
    return (
      <div style={{ width: '100%', height: '100%', background: bg, padding: '6% 8%', display: 'flex', flexDirection: 'column' }}>
        <div style={labelStyle}>Investment</div>
        <h1 style={{ ...fontDisplay, fontSize: 44, margin: '14px 0 24px' }}>{slide.headline}</h1>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, flex: 1 }}>
          {[
            { name: 'Foundation', price: '8,000', items: ['1 funnel', 'Email setup', 'Monthly report'] },
            { name: 'Growth',     price: '18,000', items: ['Full funnel ops', 'Sequences + segments', 'Weekly call'], featured: true },
            { name: 'Partnership',price: '35,000', items: ['Everything in Growth', 'Custom dev', 'On-demand'] },
          ].map(t => (
            <div key={t.name} style={{ padding: 24, border: '1px solid', borderColor: t.featured ? accent : (isDark ? '#262626' : '#d4d4d4'), background: t.featured ? (isDark ? 'rgba(34,197,94,0.06)' : 'rgba(34,197,94,0.06)') : 'transparent', display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div style={{ ...labelStyle, color: t.featured ? accent : dim }}>{t.name}</div>
              <div className="mono" style={{ fontSize: 36, fontWeight: 500, color: fg, lineHeight: 1 }}>AED {t.price}<span style={{ fontSize: 14, color: dim, marginLeft: 4 }}>/mo</span></div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13, color: dim }}>
                {t.items.map(i => <div key={i}>· {i}</div>)}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
  if (slide.kind === 'cta') {
    return (
      <div style={{ width: '100%', height: '100%', background: bg, padding: '8%', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'flex-start' }}>
        <div style={{ width: 60, height: 3, background: accent, marginBottom: 28 }}></div>
        <h1 style={{ ...fontDisplay, fontSize: 80, margin: 0 }}>{slide.headline}</h1>
        <button style={{ marginTop: 36, padding: '14px 28px', background: accent, color: '#0a0a0a', border: 'none', fontWeight: 700, fontSize: 16, cursor: 'pointer' }}>Accept proposal →</button>
      </div>
    );
  }
  return <div style={{ width: '100%', height: '100%', background: bg, padding: 80, color: fg }}>{slide.kind}</div>;
}

function PublicViewer({ slides, theme, onClose }) {
  const [idx, setIdx] = useState(0);
  React.useEffect(() => {
    const onKey = e => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowRight' || e.key === ' ') setIdx(i => Math.min(slides.length - 1, i + 1));
      if (e.key === 'ArrowLeft') setIdx(i => Math.max(0, i - 1));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [slides.length, onClose]);

  const isLast = idx === slides.length - 1;

  return (
    <div style={{ position: 'fixed', inset: 0, background: '#000', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
      <div style={{ width: '90%', maxWidth: 1280, aspectRatio: '16/9' }}>
        <SlideRender slide={slides[idx]} theme={theme} />
      </div>
      <div style={{ position: 'absolute', top: 16, right: 16, display: 'flex', gap: 8 }}>
        <button className="btn btn-sm" onClick={onClose}><Icon name="x" size={11} /> Exit</button>
      </div>
      <div style={{ position: 'absolute', bottom: 20, left: '50%', transform: 'translateX(-50%)', display: 'flex', alignItems: 'center', gap: 14, padding: '8px 14px', background: 'rgba(20,20,20,0.9)', border: '1px solid var(--divider)' }}>
        <button className="btn btn-ghost btn-icon" onClick={() => setIdx(i => Math.max(0, i - 1))}><Icon name="chevLeft" size={14} /></button>
        <span className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{idx + 1} / {slides.length}</span>
        <button className="btn btn-ghost btn-icon" onClick={() => setIdx(i => Math.min(slides.length - 1, i + 1))}><Icon name="chevRight" size={14} /></button>
        {isLast && <button className="btn btn-primary" style={{ marginLeft: 14 }}>Accept proposal →</button>}
      </div>
    </div>
  );
}

Object.assign(window, { Documents, DocumentBuilder, PublicViewer });
