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

/* ============================================================
   FUNNELS LIST + BUILDER
   The funnel builder = a list of pages stacked in sequence.
   Each page is its own HTML — we render a placeholder lineup.
   ============================================================ */

function Funnels({ goto }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Marketing</div>
          <h1 className="page-title">Funnels</h1>
          <div className="page-subtitle">{window.FUNNELS.length} funnels · {window.FUNNELS.filter(f => f.status === 'live').length} live</div>
        </div>
        <div className="page-header-right">
          <button className="btn btn-primary" onClick={() => goto('funnel-builder', 'f1')}><Icon name="plus" size={12} /> New funnel</button>
        </div>
      </div>
      <div style={{ flex: 1, overflow: 'auto', padding: 20 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 12 }}>
          {window.FUNNELS.map(f => (
            <div key={f.id} className="card" style={{ padding: 0, cursor: 'pointer' }} onClick={() => goto('funnel-builder', f.id)}>
              <div style={{ aspectRatio: '16/9', background: 'var(--raised)', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                <Icon name="funnels" size={32} style={{ color: 'var(--text-dim)' }} />
                <div style={{ position: 'absolute', top: 10, left: 10 }}>
                  <StatusPill status={f.status} />
                </div>
              </div>
              <div style={{ padding: 14 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', marginBottom: 4 }}>{f.name}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginBottom: 10 }}>lineagroup.ae/{f.slug}</div>
                <div style={{ display: 'flex', gap: 14 }}>
                  <div><div className="mono" style={{ fontSize: 14, color: 'var(--text)' }}>{f.submissions}</div><div className="label" style={{ marginTop: 2 }}>Subs</div></div>
                  <div><div className="mono" style={{ fontSize: 14, color: 'var(--accent)' }}>{f.conversion}%</div><div className="label" style={{ marginTop: 2 }}>Conv</div></div>
                  <div><div className="mono" style={{ fontSize: 14, color: 'var(--text)' }}>{f.pages}</div><div className="label" style={{ marginTop: 2 }}>Pages</div></div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function FunnelBuilder({ funnelId, goto }) {
  const f = window.FUNNELS.find(x => x.id === funnelId) || window.FUNNELS[0];
  const [selectedPage, setSelectedPage] = useState(0);
  const [device, setDevice] = useState('desktop');

  const pages = [
    { id: 1, label: 'Landing — Hero',          slug: '/' },
    { id: 2, label: 'Step 2 — Application',    slug: '/apply' },
    { id: 3, label: 'Step 3 — Calendar',       slug: '/book' },
    { id: 4, label: 'Confirmation — Thank You', slug: '/confirm' },
  ].slice(0, f.pages);

  const blocks = ['Hero', 'Video VSL', 'Body Copy', 'Form', 'Testimonial', 'FAQ', 'Footer', 'Custom Code'];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr 280px', height: '100%', overflow: 'hidden' }}>
      {/* Left: page list */}
      <div style={{ borderRight: '1px solid var(--divider)', overflowY: 'auto', display: 'flex', flexDirection: 'column' }}>
        <div style={{ padding: 16, borderBottom: '1px solid var(--divider)' }}>
          <button className="btn btn-ghost btn-sm" style={{ marginBottom: 10, padding: '4px 6px' }} onClick={() => goto('funnels')}>
            <Icon name="chevLeft" size={12} /> Funnels
          </button>
          <div style={{ fontSize: 13, fontWeight: 600 }}>{f.name}</div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 2 }}>/{f.slug}</div>
        </div>
        <div style={{ padding: 12 }}>
          <div className="label" style={{ marginBottom: 10, padding: '0 4px' }}>Pages · {pages.length}</div>
          {pages.map((p, i) => (
            <div key={p.id} onClick={() => setSelectedPage(i)} style={{
              padding: 10, border: '1px solid', borderColor: i === selectedPage ? 'var(--accent)' : 'var(--divider)',
              marginBottom: 6, cursor: 'pointer', background: i === selectedPage ? 'var(--raised)' : 'transparent',
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <div style={{ width: 16, height: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg)', border: '1px solid var(--divider)', fontSize: 9, color: 'var(--text-secondary)' }} className="mono">{i+1}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{p.label}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{p.slug}</div>
              </div>
              <Icon name="drag" size={11} style={{ color: 'var(--text-dim)' }} />
            </div>
          ))}
          <button className="btn btn-sm" style={{ width: '100%', marginTop: 4, justifyContent: 'center' }}><Icon name="plus" size={11} /> Add page</button>
        </div>
      </div>

      {/* Middle: 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 }}>
          <div style={{ display: 'flex', border: '1px solid var(--divider)' }}>
            {['desktop', 'tablet', 'mobile'].map(d => (
              <button key={d} onClick={() => setDevice(d)} className="btn btn-sm" style={{
                background: device === d ? 'var(--raised)' : 'transparent',
                borderColor: 'transparent', borderRadius: 0, textTransform: 'capitalize',
              }}>{d}</button>
            ))}
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <button className="btn btn-sm"><Icon name="eye" size={11} /> Preview</button>
            <button className="btn btn-sm"><Icon name="link" size={11} /> Domain</button>
            <button className="btn btn-primary btn-sm"><Icon name="globe" size={11} /> Publish</button>
          </div>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: 24, display: 'flex', justifyContent: 'center' }}>
          <div style={{
            width: device === 'desktop' ? '100%' : device === 'tablet' ? 768 : 380,
            maxWidth: device === 'desktop' ? 1100 : '100%',
            background: 'var(--surface)', border: '1px solid var(--divider)',
          }}>
            {/* Mock landing page */}
            <div style={{ padding: 40, borderBottom: '1px solid var(--divider)', textAlign: 'center' }}>
              <div className="label" style={{ marginBottom: 14 }}>Hero</div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontStretch: '75%', fontWeight: 800, fontSize: 36, margin: 0, letterSpacing: '-0.02em', maxWidth: 600, marginInline: 'auto' }}>The 7-Day Funnel Audit For DTC Brands.</h2>
              <p style={{ color: 'var(--text-secondary)', maxWidth: 480, margin: '14px auto 24px', fontSize: 14 }}>We tear down your current funnel, identify the leaks, and hand you a 7-day fix plan. Free.</p>
              <button className="btn btn-primary" style={{ padding: '10px 18px' }}>Get the audit →</button>
            </div>
            <div style={{ padding: 40, borderBottom: '1px solid var(--divider)' }}>
              <div className="label" style={{ marginBottom: 14 }}>Video VSL</div>
              <div style={{ aspectRatio: '16/9', background: 'var(--bg)', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid var(--divider)' }}>
                <Icon name="play" size={32} style={{ color: 'var(--accent)' }} />
              </div>
            </div>
            <div style={{ padding: 40, borderBottom: '1px solid var(--divider)' }}>
              <div className="label" style={{ marginBottom: 14 }}>Form</div>
              <div style={{ display: 'grid', gap: 8, maxWidth: 360, marginInline: 'auto' }}>
                <input className="input" placeholder="Full name" style={{ padding: 10 }} />
                <input className="input" placeholder="Work email" style={{ padding: 10 }} />
                <input className="input" placeholder="Brand URL" style={{ padding: 10 }} />
                <button className="btn btn-primary" style={{ padding: 10, justifyContent: 'center' }}>Send me the audit</button>
              </div>
            </div>
            <div style={{ padding: 24, color: 'var(--text-dim)', fontSize: 11, textAlign: 'center' }}>
              <div className="label" style={{ marginBottom: 6 }}>Footer</div>
              © Linea Group · lineagroup.ae
            </div>
          </div>
        </div>
      </div>

      {/* Right: blocks library + properties */}
      <div style={{ borderLeft: '1px solid var(--divider)', overflowY: 'auto' }}>
        <div style={{ padding: 16, borderBottom: '1px solid var(--divider)' }}>
          <div className="label" style={{ marginBottom: 12 }}>Blocks</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
            {blocks.map(b => {
              const isCode = b === 'Custom Code';
              return (
                <div key={b} style={{
                  padding: 10,
                  background: isCode ? 'transparent' : 'var(--raised)',
                  border: isCode ? '1px dashed var(--accent)' : '1px solid var(--divider)',
                  textAlign: 'center',
                  fontSize: 11,
                  cursor: 'grab',
                  color: isCode ? 'var(--accent)' : 'var(--text-secondary)',
                  fontFamily: isCode ? 'var(--font-mono, ui-monospace, monospace)' : 'inherit',
                  letterSpacing: isCode ? '0.04em' : 'normal',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: 6,
                }}>
                  {isCode && <span style={{ fontSize: 10, opacity: 0.8 }}>{'</>'}</span>}
                  {b}
                </div>
              );
            })}
          </div>
        </div>
        <div style={{ padding: 16 }}>
          <div className="label" style={{ marginBottom: 12 }}>Properties · Hero</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <div>
              <div className="label" style={{ marginBottom: 4 }}>Heading</div>
              <input className="input" defaultValue="The 7-Day Funnel Audit…" />
            </div>
            <div>
              <div className="label" style={{ marginBottom: 4 }}>CTA Label</div>
              <input className="input" defaultValue="Get the audit →" />
            </div>
            <div>
              <div className="label" style={{ marginBottom: 4 }}>CTA Link</div>
              <input className="input" defaultValue="/apply" />
            </div>
            <div>
              <div className="label" style={{ marginBottom: 4 }}>Background</div>
              <div style={{ display: 'flex', gap: 4 }}>
                {['#0a0a0a', '#141414', '#22c55e', '#ffffff'].map(c => (
                  <div key={c} style={{ width: 24, height: 24, background: c, border: '1px solid var(--divider)', cursor: 'pointer' }}></div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Funnels, FunnelBuilder });
