// app.jsx — App shell: Topbar, NavPills, Router, Auth gate, ReactDOM mount
// Final file in load order. Depends on all window.* exports from previous JSX files.

const NAV_ITEMS = [
  { id:'home',         label:'Home',         icon:'home'     },
  { id:'clients',      label:'Clients',      icon:'users'    },
  { id:'onboarding',   label:'Onboarding',   icon:'check'    },
  { id:'provisioning', label:'Provisioning', icon:'wrench'   },
  { id:'website',      label:'Website',      icon:'globe'    },
  { id:'finance',      label:'Finance',      icon:'money',   alert:true },
  { id:'leads',        label:'Leads',        icon:'lead'     },
  { id:'diary',        label:'Diary',        icon:'cal'      },
  { id:'documents',    label:'Documents',    icon:'doc'      },
  { id:'reports',      label:'Reports',      icon:'chart'    },
  { id:'progress',     label:'Progress',     icon:'chart'    },
  { id:'agents',       label:'Agents',       icon:'bot'      },
  { id:'infrastructure', label:'Stack',      icon:'globe'    },
  { id:'settings',     label:'Settings',     icon:'settings' },
];

/* ─── Topbar ────────────────────────────────────────────────────────── */
function Topbar({ page, setPage, onSignOut }) {
  const mailNeedsCheck = (Date.now() - +(localStorage.getItem('pcc-mail-checked-at') || 0)) > 4 * 3600 * 1000;
  return (
    <div className="topbar">
      <div className="topbar-brand">
        <BrandLogo size="md" />
        <div>
          <div className="brand-name">Pinnacle</div>
          <div className="brand-sub">Command Centre</div>
        </div>
      </div>
      <div className="topbar-actions">
        <div className="icon-btn" title="New client" style={{ cursor:'pointer' }} onClick={() => setPage('clients')}><Icon name="plus" size={18} /></div>
        <div className="icon-btn" title="Pinnacle Mail" style={{ cursor:'pointer', position:'relative' }}
          onClick={() => { window.open('https://mail.google.com/mail/u/info@pinnaclepa.biz/#inbox','_blank','noopener'); localStorage.setItem('pcc-mail-checked-at', String(Date.now())); }}>
          <Icon name="mail" size={18} />
          {mailNeedsCheck && <div className="flicker-dot" style={{ position:'absolute', top:2, right:2, width:7, height:7 }} />}
        </div>
        <div className="icon-btn" title="Activity" style={{ position:'relative', cursor:'pointer' }} onClick={() => setPage('home')}>
          <Icon name="bell" size={18} />
          <div className="ruby-dot" />
        </div>
        <div className="user-chip">
          <div className="avatar-initial">T</div>
          <span style={{ fontSize:13, fontWeight:600 }}>Tiaan</span>
        </div>
        <div className="icon-btn" title="Toggle theme" style={{ cursor:'pointer' }}
          onClick={() => window.applyTheme(document.documentElement.getAttribute('data-theme') ? 'default' : 'obsidian')}>
          <Icon name="sun" size={18} />
        </div>
        <div className="zoom-badge">100%</div>
        <div className="icon-btn" title="Sign out" onClick={onSignOut} style={{ cursor:'pointer' }}>
          <Icon name="signout" size={18} />
        </div>
      </div>
    </div>
  );
}

/* ─── NavPills ──────────────────────────────────────────────────────── */
function NavPills({ page, setPage }) {
  return (
    <div className="nav-pills">
      {NAV_ITEMS.map(item => (
        <div
          key={item.id}
          className={`nav-pill${page === item.id ? ' active' : ''}`}
          onClick={() => setPage(item.id)}
          style={{ position:'relative' }}
        >
          {item.label}
          {item.alert && <div className="pill-dot" />}
        </div>
      ))}
    </div>
  );
}

/* ─── Page router ───────────────────────────────────────────────────── */
function renderPage(page) {
  const map = {
    home:         window.HomePage,
    clients:      window.ClientsPage,
    onboarding:   window.OnboardingPage,
    provisioning: window.ProvisioningPage,
    website:      window.WebsitePage,
    finance:      window.FinancePage,
    leads:        window.LeadsPage,
    diary:        window.DiaryPage,
    documents:    window.DocumentsPage,
    reports:      window.ReportsPage,
    progress:     window.ProgressPage,
    agents:       window.AgentsPage,
    infrastructure: window.InfrastructurePage,
    settings:     window.SettingsPage,
  };
  const Component = map[page];
  if (!Component) {
    return (
      <div style={{ padding:40, textAlign:'center', color:'var(--muted)', fontStyle:'italic' }}>
        Module coming soon
      </div>
    );
  }
  return <Component />;
}

/* ─── Login gate ────────────────────────────────────────────────────── */
// Single-user Supabase auth (info@pinnaclepa.biz). Gates the whole app.
function LoginGate({ onAuthed }) {
  const ownerEmail = (window.PCC_CONFIG && window.PCC_CONFIG.OWNER_EMAIL) || '';
  const [email, setEmail]   = React.useState(ownerEmail);
  const [pw, setPw]         = React.useState('');
  const [busy, setBusy]     = React.useState(false);
  const [error, setError]   = React.useState('');

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setError(''); setBusy(true);
    const res = await window.pccAuth.signIn(email.trim(), pw);
    setBusy(false);
    if (res.ok) { onAuthed(); }
    else { setError(res.error || 'Sign-in failed'); setPw(''); }
  }

  const GOLD = 'linear-gradient(135deg, #E2C275 0%, #B8893E 50%, #8B6914 100%)';

  return (
    <div style={{
      minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center',
      background:'radial-gradient(120% 120% at 50% 0%, #2A3142 0%, #1F2433 60%, #161A26 100%)',
      padding:24, fontFamily:"'Manrope', system-ui, sans-serif",
    }}>
      <form onSubmit={submit} style={{
        width:'100%', maxWidth:380, background:'rgba(31,36,51,0.72)',
        border:'1px solid rgba(226,194,117,0.28)', borderRadius:18, padding:'40px 34px',
        boxShadow:'0 24px 60px rgba(0,0,0,0.45)', textAlign:'center',
      }}>
        <div style={{
          width:64, height:64, margin:'0 auto 18px', borderRadius:16,
          display:'flex', alignItems:'center', justifyContent:'center',
          background:'rgba(226,194,117,0.10)', border:'1px solid rgba(226,194,117,0.3)',
        }}>
          <BrandLogo size="md" />
        </div>
        <div style={{
          fontSize:11, fontWeight:700, letterSpacing:'0.22em', textTransform:'uppercase',
          color:'#E2C275', marginBottom:8,
        }}>Pinnacle PA</div>
        <h1 style={{
          margin:'0 0 6px', fontFamily:"'Cormorant Garamond', serif", fontWeight:600,
          fontSize:34, lineHeight:1.1, color:'#F4F1EC',
        }}>Command <em style={{ fontStyle:'italic', fontWeight:400, color:'#E2C275' }}>Centre</em></h1>
        <p style={{ margin:'0 0 26px', fontSize:13, color:'rgba(244,241,236,0.6)' }}>
          Sign in to your control room
        </p>

        {error && (
          <div role="alert" style={{
            background:'rgba(200,60,60,0.14)', border:'1px solid rgba(220,90,90,0.4)',
            color:'#F3C0C0', borderRadius:10, padding:'10px 12px', fontSize:12.5,
            marginBottom:16, textAlign:'left',
          }}>{error}</div>
        )}

        <label style={{ display:'block', textAlign:'left', fontSize:11, fontWeight:600,
          letterSpacing:'0.14em', textTransform:'uppercase', color:'rgba(244,241,236,0.55)', marginBottom:6 }}>
          Email
        </label>
        <input
          type="email" value={email} onChange={e => setEmail(e.target.value)}
          autoComplete="username" required placeholder="you@pinnaclepa.biz"
          style={inputStyle}
        />

        <label style={{ display:'block', textAlign:'left', fontSize:11, fontWeight:600,
          letterSpacing:'0.14em', textTransform:'uppercase', color:'rgba(244,241,236,0.55)', margin:'16px 0 6px' }}>
          Password
        </label>
        <input
          type="password" value={pw} onChange={e => setPw(e.target.value)}
          autoComplete="current-password" required placeholder="••••••••"
          style={inputStyle}
        />

        <button type="submit" disabled={busy} style={{
          width:'100%', marginTop:24, padding:'14px', border:'none', borderRadius:11,
          background:GOLD, color:'#1F2433', fontWeight:700, fontSize:14, letterSpacing:'0.02em',
          cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.7 : 1,
          fontFamily:"'Manrope', sans-serif",
        }}>
          {busy ? 'Signing in…' : 'Sign In'}
        </button>

        <div style={{ marginTop:22, fontSize:11.5, color:'rgba(244,241,236,0.4)' }}>
          Single user · {ownerEmail || 'info@pinnaclepa.biz'}
        </div>
      </form>
    </div>
  );
}

const inputStyle = {
  width:'100%', boxSizing:'border-box', padding:'12px 14px', borderRadius:11,
  border:'1px solid rgba(226,194,117,0.22)', background:'rgba(0,0,0,0.25)',
  color:'#F4F1EC', fontSize:14, fontFamily:"'Manrope', sans-serif", outline:'none',
};

/* ─── Persistent YouTube Player ────────────────────────────────────── */
// Mounted once in the app shell — the iframe is NEVER unmounted, so audio
// continues playing across all page navigations. Volume is sent via postMessage
// using YouTube's enablejsapi=1 channel. Uses height:0 (not display:none) to
// keep the iframe alive while collapsed.
function PersistentYTPlayer() {
  const [url, setUrl]      = React.useState(() => localStorage.getItem('pcc-yt-url') || '');
  const [videoId, setVid]  = React.useState(() => window.parseYouTubeId ? window.parseYouTubeId(localStorage.getItem('pcc-yt-url') || '') : null);
  const [volume, setVol]   = React.useState(() => parseInt(localStorage.getItem('pcc-yt-vol') || '80'));
  const [expanded, setExp] = React.useState(false);
  const iframeRef          = React.useRef(null);

  // Expose global API so YouTubeCard (home.jsx) can trigger playback
  React.useEffect(() => {
    window.__ytPlay = (newUrl) => {
      const id = window.parseYouTubeId ? window.parseYouTubeId(newUrl) : null;
      if (!id) return;
      setUrl(newUrl); setVid(id);
      localStorage.setItem('pcc-yt-url', newUrl);
      setExp(true);
    };
    window.__ytClear = () => {
      setUrl(''); setVid(null); setExp(false);
      localStorage.removeItem('pcc-yt-url');
    };
  }, []);

  function sendCmd(func, args) {
    iframeRef.current?.contentWindow?.postMessage(
      JSON.stringify({ event:'command', func, args }), '*'
    );
  }

  function handleVol(v) {
    const val = parseInt(v);
    setVol(val);
    localStorage.setItem('pcc-yt-vol', String(val));
    sendCmd('setVolume', [val]);
  }

  function handleGo() {
    if (url && window.__ytPlay) window.__ytPlay(url);
  }

  // Pick volume icon based on level
  const volPath = volume === 0
    ? 'M11 5L6 9H2v6h4l5 4V5z M23 9l-6 6 M17 9l6 6'
    : volume < 50
    ? 'M11 5L6 9H2v6h4l5 4V5z M15.54 8.46a5 5 0 0 1 0 7.07'
    : 'M11 5L6 9H2v6h4l5 4V5z M15.54 8.46a5 5 0 0 1 0 7.07 M19.07 4.93a10 10 0 0 1 0 14.14';

  return (
    <div className={`yt-bar${videoId ? ' yt-bar-active' : ''}`}>
      {/* ── Video panel: height:0 keeps iframe in DOM (audio live) when collapsed ── */}
      <div className="yt-bar-panel" style={{ height: expanded && videoId ? 202 : 0 }}>
        {videoId && (
          <iframe
            ref={iframeRef}
            key={videoId}
            src={`https://www.youtube.com/embed/${videoId}?autoplay=1&rel=0&enablejsapi=1`}
            allow="autoplay; encrypted-media"
            allowFullScreen
            frameBorder="0"
            title="YouTube"
            onLoad={() => setTimeout(() => sendCmd('setVolume', [volume]), 900)}
            style={{ width:'100%', height:'100%', border:'none' }}
          />
        )}
      </div>
      {/* ── Control bar ── */}
      <div className="yt-bar-row">
        <button className="yt-bar-btn" onClick={() => setExp(e => !e)} title={expanded ? 'Hide video' : 'Show video'}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            {expanded
              ? <polyline points="18 15 12 9 6 15" />
              : <polyline points="6 9 12 15 18 9" />}
          </svg>
        </button>
        {videoId && <div className="yt-live-dot" />}
        <span className="yt-bar-label">YouTube</span>
        <input
          className="yt-bar-input"
          value={url}
          onChange={e => setUrl(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && handleGo()}
          placeholder="Paste YouTube URL — audio persists across all pages…"
        />
        <button className="yt-bar-btn" onClick={handleGo} title="Play">▶</button>
        {videoId && (
          <button className="yt-bar-btn" onClick={() => window.__ytClear()} title="Stop">■</button>
        )}
        {/* External volume control — sends postMessage to the iframe */}
        <svg className="yt-vol-icon" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d={volPath} strokeLinecap="round" strokeLinejoin="round" />
        </svg>
        <input
          type="range" min="0" max="100" value={volume}
          onChange={e => handleVol(e.target.value)}
          className="yt-vol-slider"
          title={`Volume ${volume}%`}
        />
        <span className="yt-vol-pct">{volume}%</span>
      </div>
    </div>
  );
}

/* ─── Theme helper (global) ─────────────────────────────────────────── */
window.applyTheme = function(themeId) {
  if (themeId === 'default') {
    document.documentElement.removeAttribute('data-theme');
  } else {
    document.documentElement.setAttribute('data-theme', themeId);
  }
  localStorage.setItem('pcc-theme', themeId);
};

/* ─── App root ──────────────────────────────────────────────────────── */
function App({ onSignOut }) {
  const [page, setPage] = React.useState('home');
  window.__nav = setPage;   // expose for QA / deep-linking

  // Restore saved theme on mount
  React.useEffect(() => {
    const saved = localStorage.getItem('pcc-theme');
    if (saved && saved !== 'default') {
      document.documentElement.setAttribute('data-theme', saved);
    }
  }, []);

  return (
    <div className="app-shell">
      <Topbar page={page} setPage={setPage} onSignOut={onSignOut} />
      <NavPills page={page} setPage={setPage} />
      <div className="app-body">
        {renderPage(page)}
      </div>
      <PersistentYTPlayer />
    </div>
  );
}

/* ─── Root: auth gate ───────────────────────────────────────────────── */
function Root() {
  const [authed, setAuthed] = React.useState(() => !!window.pccAuth.getSession());
  const [checking, setChecking] = React.useState(true);

  // On mount, refresh a stale-but-present session before deciding.
  React.useEffect(() => {
    let alive = true;
    window.pccAuth.ensureSession().then(s => {
      if (!alive) return;
      setAuthed(!!s);
      setChecking(false);
    });
    return () => { alive = false; };
  }, []);

  function handleSignOut() {
    window.pccAuth.signOut().finally(() => setAuthed(false));
  }

  if (checking && !authed) {
    return (
      <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center',
        background:'#1F2433', color:'rgba(244,241,236,0.5)', fontFamily:"'Manrope', sans-serif" }}>
        Loading…
      </div>
    );
  }

  if (!authed) return <LoginGate onAuthed={() => setAuthed(true)} />;
  return <App onSignOut={handleSignOut} />;
}

/* ─── Mount ─────────────────────────────────────────────────────────── */
ReactDOM.createRoot(document.getElementById('root')).render(
  React.createElement(Root)
);
