// Testing Ads — root app (state + router + device toggle)

const { Sidebar, Btn, Avatar, StatusPill } = window.WF;
const { PipelinePage } = window.TA_PIPELINE;
const { DetailScreen, AdLiveScreen, InfluencerScreen } = window.TA_SCREENS;

// ——— Store (reducer simple) ———
const initialState = /*EDITMODE-BEGIN*/{
  "staleThresholdDays": 4,
  "primaryAccent": "#2c4cf5"
}/*EDITMODE-END*/;

function videosReducer(state, action) {
  switch (action.type) {
    case 'moveTo': {
      return state.map(v => v.id === action.id ? { ...v, status: action.status, ...(action.extra || {}) } : v);
    }
    case 'reset':
      return JSON.parse(JSON.stringify(window.TA_VIDEOS_INITIAL));
    default:
      return state;
  }
}

// ——— Page header (titre + sous-titre + toolbar) ———
function Header({ title, subtitle, kicker, toolbar }) {
  return (
    <header style={{ padding: '18px 22px 8px', display: 'flex', alignItems: 'flex-end', gap: 16 }}>
      <div style={{ flex: 1, minWidth: 0 }}>
        {kicker && (
          <div style={{ font: '500 11px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, marginBottom: 2 }}>{kicker}</div>
        )}
        {title && (
          <h1 style={{ margin: 0, font: '700 28px var(--font-sans)', color: 'var(--ink)', letterSpacing: -0.5 }}>{title}</h1>
        )}
        {subtitle && (
          <div style={{ marginTop: 2, font: '400 13px var(--font-sans)', color: 'var(--ink-3)' }}>{subtitle}</div>
        )}
      </div>
      {toolbar && <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>{toolbar}</div>}
    </header>
  );
}

// ——— Mobile top bar ———
function MobileTopBar({ title, sub, onMenu }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '12px 14px', background: 'var(--paper)', borderBottom: '1px solid var(--border)',
    }}>
      <div style={{ width: 26, height: 26, borderRadius: 6, background: '#111', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', font: '800 10px var(--font-sans)' }}>JA</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: '700 14px var(--font-sans)' }}>{title}</div>
        {sub && <div style={{ font: '500 11px var(--font-sans)', color: 'var(--ink-3)' }}>{sub}</div>}
      </div>
      <Avatar name="Katlyn" size={26} />
    </div>
  );
}

// ——— App principal ———
function App() {
  const [videos, dispatch] = React.useReducer(videosReducer, null, () => JSON.parse(JSON.stringify(window.TA_VIDEOS_INITIAL)));
  const [route, setRoute] = React.useState({ name: 'pipeline' });
  const [device, setDevice] = React.useState('desktop'); // 'desktop' | 'mobile'

  const goto = (r) => setRoute(r);
  const back = () => setRoute({ name: 'pipeline' });

  const ds = { videos };
  const isMobile = device === 'mobile';

  // ——— Vue principale (dans le device frame) ———
  const renderMain = () => {
    if (route.name === 'pipeline') {
      const subTitle = `${videos.filter(v => !['scaled','killed'].includes(v.status)).length} vidéos en flux — semaine du 21 mai`;
      return (
        <>
          <Header
            kicker="Testing Ads"
            title="Pipeline"
            subtitle={subTitle}
            toolbar={
              <>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px',
                  background: 'var(--paper)', border: '1px solid var(--border-2)', borderRadius: 8,
                  color: 'var(--ink-3)', font: '500 12.5px var(--font-sans)', minWidth: 220,
                }}>
                  <svg width="13" height="13" viewBox="0 0 12 12"><circle cx="5" cy="5" r="3.5" fill="none" stroke="currentColor" strokeWidth="1.3"/><path d="M8 8 L11 11" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>
                  Rechercher (influenceuse, code…)
                </div>
                <Btn variant="ghost">Activité récente ▾</Btn>
                <Btn variant="dark">+ Vidéo manuelle</Btn>
              </>
            }
          />
          <div style={{ flex: 1, minHeight: 0, padding: '8px 22px 22px', display: 'flex', flexDirection: 'column' }}>
            <PipelinePage
              state={ds}
              dispatch={dispatch}
              onOpenVideo={(v) => goto({ name: 'detail', id: v.id })}
              onOpenInfluencer={(inf) => goto({ name: 'influencer', handle: inf.handle })}
            />
          </div>
        </>
      );
    }
    if (route.name === 'detail') {
      const video = videos.find(v => v.id === route.id);
      if (!video) return <div style={{ padding: 24 }}>Vidéo introuvable</div>;
      const inf = window.TA_INFLUENCERS[video.inf];
      const status = window.TA_STATUS_META[video.status];
      return (
        <>
          <Header
            kicker={`Pipeline · ${inf.handle}`}
            title={inf.name}
            subtitle={`Reçue ${window.TA_FORMAT.age(video.receivedHours)} · source ${video.dur} · contrat #${420 + parseInt(video.id.slice(1)) || 421}`}
            toolbar={<><StatusPill emoji={status.emoji} variant={status.variant}>{status.label}</StatusPill></>}
          />
          <DetailScreen
            video={video} isMobile={isMobile}
            onBack={back}
            onOpenInfluencer={(inf) => goto({ name: 'influencer', handle: inf.handle })}
            onOpenAdLive={(v) => goto({ name: 'ad-live', id: v.id })}
            dispatch={dispatch}
          />
        </>
      );
    }
    if (route.name === 'ad-live') {
      const video = videos.find(v => v.id === route.id);
      if (!video) return <div style={{ padding: 24 }}>Ad introuvable</div>;
      const inf = window.TA_INFLUENCERS[video.inf];
      return (
        <>
          <Header kicker="Testing Ads / Live" title={`${inf.handle} · J${video.daysLive}`} subtitle="Performances en direct depuis Meta Ads Manager" />
          <AdLiveScreen
            video={video}
            onBack={back}
            onOpenInfluencer={(inf) => goto({ name: 'influencer', handle: inf.handle })}
            dispatch={dispatch}
          />
        </>
      );
    }
    if (route.name === 'influencer') {
      const inf = Object.values(window.TA_INFLUENCERS).find(i => i.handle === route.handle);
      if (!inf) return <div style={{ padding: 24 }}>Influenceuse introuvable</div>;
      return (
        <>
          <Header kicker="Annuaire" title={inf.name} subtitle={inf.handle} />
          <InfluencerScreen
            influencer={inf}
            allVideos={videos}
            onBack={back}
            onOpenVideo={(v) => goto({ name: 'detail', id: v.id })}
          />
        </>
      );
    }
    return null;
  };

  // —— Mobile : on cache la sidebar et on remplace par une topbar minimaliste
  const mobileRoute = () => {
    if (route.name === 'detail') {
      const video = videos.find(v => v.id === route.id);
      if (!video) return null;
      const inf = window.TA_INFLUENCERS[video.inf];
      const status = window.TA_STATUS_META[video.status];
      return (
        <>
          <MobileTopBar title={inf?.name || 'Vidéo'} sub={inf?.handle} />
          <DetailScreen
            video={video} isMobile
            onBack={back}
            onOpenInfluencer={(inf) => goto({ name: 'influencer', handle: inf.handle })}
            onOpenAdLive={(v) => goto({ name: 'ad-live', id: v.id })}
            dispatch={dispatch}
          />
        </>
      );
    }
    // Mobile pipeline (vue empilée verticale)
    return (
      <>
        <MobileTopBar title="Pipeline" sub="3 attendent — Katlyn" />
        <div className="scroll-y" style={{ flex: 1, padding: 12 }}>
          {/* Tabs statut */}
          <div style={{ display: 'flex', gap: 5, marginBottom: 10, overflow: 'auto', paddingBottom: 4 }}>
            <window.WF.FilterPill active count={videos.filter(v => v.status === 'toEdit').length}>À monter</window.WF.FilterPill>
            <window.WF.FilterPill count={videos.filter(v => v.status === 'editing').length}>Montage</window.WF.FilterPill>
            <window.WF.FilterPill count={videos.filter(v => v.status === 'edited').length}>Montée</window.WF.FilterPill>
            <window.WF.FilterPill count={videos.filter(v => v.status === 'testing').length}>Testing</window.WF.FilterPill>
          </div>
          {/* Liste empilée — À monter en premier */}
          {['toEdit', 'editing', 'edited', 'testing'].map(st => {
            const items = videos.filter(v => v.status === st);
            if (items.length === 0) return null;
            const s = window.TA_STATUS_META[st];
            return (
              <div key={st} style={{ marginBottom: 14 }}>
                <div style={{ font: '700 11px var(--font-sans)', color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 1, margin: '4px 2px 8px' }}>
                  {s.emoji} {s.label} · {items.length}
                </div>
                {items.map(v => {
                  const inf = window.TA_INFLUENCERS[v.inf];
                  const stale = window.TA_FORMAT.isStale(v, 4);
                  return (
                    <window.WF.Card key={v.id} style={{ padding: 10, marginBottom: 8, borderColor: stale ? '#fda4a4' : 'var(--border)' }} onClick={() => goto({ name: 'detail', id: v.id })}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <div style={{ width: 56, height: 64, flex: 'none', borderRadius: 7, overflow: 'hidden' }}>
                          <window.WF.Thumb ratio={64/56} dur={v.dur} />
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <Avatar name={inf.name} size={20} />
                            <span style={{ font: '600 13px var(--font-sans)' }}>{inf.handle}</span>
                          </div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
                            <window.WF.PromoCode code={inf.code} size="sm" />
                            {stale && <StatusPill variant="red" size="sm">⚠ {window.TA_FORMAT.ageShort(v.receivedHours)}</StatusPill>}
                          </div>
                        </div>
                        <Btn size="sm" variant={st === 'toEdit' ? 'dark' : st === 'edited' ? 'success' : 'ghost'}>
                          {st === 'toEdit' ? 'Prendre' : st === 'edited' ? '📡' : st === 'testing' ? '→' : '→'}
                        </Btn>
                      </div>
                    </window.WF.Card>
                  );
                })}
              </div>
            );
          })}
        </div>
      </>
    );
  };

  return (
    <>
      {/* Toolbar device en haut à droite */}
      <div className="device-toolbar">
        <button className={device === 'desktop' ? 'active' : ''} onClick={() => setDevice('desktop')}>🖥 Desktop</button>
        <button className={device === 'mobile' ? 'active' : ''} onClick={() => setDevice('mobile')}>📱 Mobile</button>
      </div>

      <button className="reset-btn" onClick={() => { dispatch({ type: 'reset' }); back(); }}>
        ⟲ Reset prototype
      </button>

      <div className="device-shell" data-mode={device}>
        <div className="device-frame">
          {isMobile ? (
            <div style={{ width: '100%', height: '100%', background: 'var(--bg)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              {mobileRoute()}
            </div>
          ) : (
            <div style={{
              width: '100%', height: '100%',
              background: 'var(--bg)', color: 'var(--ink)',
              font: '500 13px var(--font-sans)',
              display: 'flex', flexDirection: 'column', overflow: 'hidden',
            }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '10px 22px', borderBottom: '1px solid var(--border)',
                background: 'var(--paper)',
              }}>
                <a href="https://lja-studio.fr/" style={{
                  font: '500 12px var(--font-sans)', color: 'var(--ink-3)',
                  textDecoration: 'none', display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>← lja-studio</a>
                <div style={{ width: 1, height: 14, background: 'var(--border)' }} />
                <div style={{
                  width: 22, height: 22, borderRadius: 5,
                  background: '#111', color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  font: '800 10px var(--font-sans)',
                }}>JA</div>
                <div style={{ font: '700 13px var(--font-sans)' }}>Testing Ads</div>
              </div>
              <main style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                {renderMain()}
              </main>
            </div>
          )}
        </div>
      </div>
    </>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
