/* ================================================================
   Tracker FMN — Site Screen v2
   Views do blog com filtros de período, referrer, device e UTM
   ================================================================ */
const { useState: useStateSite, useEffect: useEffectSite, useCallback: useCallbackSite } = React;

const PERIODOS_SITE = [
  { id: 'hoje',   label: 'Hoje'          },
  { id: '7d',     label: '7 dias'        },
  { id: '30d',    label: '30 dias'       },
  { id: 'maximo', label: 'Máximo'        },
  { id: 'custom', label: 'Personalizado' },
];

function isoLocal(d) { return d.toISOString().slice(0, 10); }

function dateRangeFor(periodId) {
  const now = new Date();
  const todayStr = isoLocal(now);
  if (periodId === 'hoje') return { from: todayStr + 'T00:00:00', to: null };
  if (periodId === '7d')  { const d = new Date(now); d.setDate(d.getDate() - 7);  return { from: d.toISOString(), to: null }; }
  if (periodId === '30d') { const d = new Date(now); d.setDate(d.getDate() - 30); return { from: d.toISOString(), to: null }; }
  return { from: null, to: null };
}

function fmtDate(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

function fmtRefLabel(ref) {
  if (!ref) return 'Direto / Digitado';
  if (/google/i.test(ref))    return 'Google';
  if (/instagram/i.test(ref)) return 'Instagram';
  if (/facebook/i.test(ref))  return 'Facebook';
  if (/whatsapp/i.test(ref))  return 'WhatsApp';
  if (/youtube/i.test(ref))   return 'YouTube';
  if (/linkedin/i.test(ref))  return 'LinkedIn';
  try { return new URL(ref).hostname.replace('www.', ''); } catch { return ref; }
}

function SiteScreen() {
  const { TopBar, LucideIcon, CardKPI, SectionCard } = window;

  const [periodo, setPeriodo]         = useStateSite('7d');
  const [customFrom, setCustomFrom]   = useStateSite('');
  const [customTo, setCustomTo]       = useStateSite('');
  const [sortBy, setSortBy]           = useStateSite('views');
  const [posts, setPosts]             = useStateSite([]);
  const [events, setEvents]           = useStateSite([]);
  const [loading, setLoading]         = useStateSite(true);

  /* ── Carrega dados ─────────────────────────────────────────────── */
  const load = useCallbackSite(async () => {
    if (!window.db) return;
    setLoading(true);

    if (periodo === 'maximo') {
      const { data } = await window.db
        .from('site_post_views')
        .select('slug,titulo,views,last_view_at')
        .order('views', { ascending: false });
      setPosts(data || []);
      setEvents([]);
    } else {
      let q = window.db
        .from('site_post_view_events')
        .select('slug,titulo,viewed_at,referrer,utm_source,utm_medium,utm_campaign,device')
        .order('viewed_at', { ascending: false })
        .limit(10000);

      if (periodo === 'custom') {
        if (customFrom) q = q.gte('viewed_at', customFrom + 'T00:00:00');
        if (customTo)   q = q.lte('viewed_at', customTo   + 'T23:59:59');
      } else {
        const { from } = dateRangeFor(periodo);
        if (from) q = q.gte('viewed_at', from);
      }

      const { data } = await q;
      const evs = data || [];
      setEvents(evs);

      // Agrega por slug
      const map = {};
      evs.forEach(e => {
        if (!map[e.slug]) map[e.slug] = { slug: e.slug, titulo: e.titulo, views: 0, last_view_at: e.viewed_at };
        map[e.slug].views++;
        if (e.viewed_at > map[e.slug].last_view_at) map[e.slug].last_view_at = e.viewed_at;
        if (e.titulo && !map[e.slug].titulo) map[e.slug].titulo = e.titulo;
      });
      setPosts(Object.values(map));
    }

    setLoading(false);
  }, [periodo, customFrom, customTo]);

  useEffectSite(() => { load(); }, [load]);

  /* ── Derivados ─────────────────────────────────────────────────── */
  const totalViews = posts.reduce((s, p) => s + (p.views || 0), 0);

  const sorted = [...posts].sort((a, b) => {
    if (sortBy === 'views')   return (b.views || 0) - (a.views || 0);
    if (sortBy === 'recente') return new Date(b.last_view_at) - new Date(a.last_view_at);
    return (a.titulo || a.slug).localeCompare(b.titulo || b.slug, 'pt-BR');
  });

  const maxViews = posts.length ? Math.max(...posts.map(p => p.views || 0)) : 0;

  // Referrers
  const refMap = {};
  events.forEach(e => {
    const label = fmtRefLabel(e.referrer);
    refMap[label] = (refMap[label] || 0) + 1;
  });
  const topRefs = Object.entries(refMap).sort((a, b) => b[1] - a[1]).slice(0, 6);

  // UTM
  const utmMap = {};
  events.forEach(e => {
    if (e.utm_source) {
      const key = [e.utm_source, e.utm_medium].filter(Boolean).join(' / ');
      utmMap[key] = (utmMap[key] || 0) + 1;
    }
  });
  const topUtms = Object.entries(utmMap).sort((a, b) => b[1] - a[1]).slice(0, 5);

  // Device
  const mobile  = events.filter(e => e.device === 'mobile').length;
  const desktop = events.filter(e => e.device === 'desktop').length;
  const totalDev = mobile + desktop || 1;
  const mobilePct  = Math.round((mobile  / totalDev) * 100);
  const desktopPct = Math.round((desktop / totalDev) * 100);

  const postMaisLido = sorted[0];

  /* ── Seletor de período ────────────────────────────────────────── */
  function PeriodSelector() {
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
        {PERIODOS_SITE.map(p => (
          <button key={p.id} onClick={() => setPeriodo(p.id)}
            style={{
              padding: '6px 13px', borderRadius: 7, cursor: 'pointer',
              fontSize: 12, fontFamily: 'Roboto,sans-serif', fontWeight: 600,
              letterSpacing: '0.02em', border: '1px solid', transition: 'all 150ms',
              background: periodo === p.id ? 'rgba(234,170,65,.13)' : 'transparent',
              borderColor: periodo === p.id ? 'rgba(234,170,65,.35)' : 'rgba(255,255,255,.1)',
              color: periodo === p.id ? 'var(--fmn-gold)' : 'rgba(255,255,255,.45)',
            }}>
            {p.label}
          </button>
        ))}
        {periodo === 'custom' && (
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <input type="date" value={customFrom} onChange={e => setCustomFrom(e.target.value)}
              style={{ background: 'rgba(255,255,255,.05)', border: '1px solid rgba(255,255,255,.12)',
                borderRadius: 6, color: 'rgba(255,255,255,.8)', fontSize: 12, padding: '5px 8px',
                fontFamily: 'Roboto,sans-serif' }} />
            <span style={{ color: 'rgba(255,255,255,.3)', fontSize: 11 }}>até</span>
            <input type="date" value={customTo} onChange={e => setCustomTo(e.target.value)}
              style={{ background: 'rgba(255,255,255,.05)', border: '1px solid rgba(255,255,255,.12)',
                borderRadius: 6, color: 'rgba(255,255,255,.8)', fontSize: 12, padding: '5px 8px',
                fontFamily: 'Roboto,sans-serif' }} />
            <button onClick={load}
              style={{ padding: '5px 11px', borderRadius: 6, cursor: 'pointer',
                fontSize: 11, fontFamily: 'Roboto,sans-serif', fontWeight: 700,
                border: '1px solid rgba(234,170,65,.35)', background: 'rgba(234,170,65,.1)',
                color: 'var(--fmn-gold)' }}>
              Buscar
            </button>
          </div>
        )}
        <button onClick={load}
          style={{ padding: '6px 10px', borderRadius: 7, cursor: 'pointer',
            fontSize: 11, fontFamily: 'Roboto,sans-serif', fontWeight: 600,
            border: '1px solid rgba(255,255,255,.1)', background: 'transparent',
            color: 'rgba(255,255,255,.35)', display: 'flex', alignItems: 'center', gap: 4,
            transition: 'all 150ms' }}>
          <LucideIcon icon="refresh-cw" size={11} />
          Atualizar
        </button>
      </div>
    );
  }

  /* ── Barra de progresso ────────────────────────────────────────── */
  function Bar({ pct, color = 'var(--fmn-gold)' }) {
    return (
      <div style={{ height: 3, borderRadius: 2, background: 'rgba(255,255,255,.07)', overflow: 'hidden' }}>
        <div style={{ height: '100%', width: pct + '%', borderRadius: 2, background: color, transition: 'width 400ms' }} />
      </div>
    );
  }

  /* ── Render ────────────────────────────────────────────────────── */
  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflowY: 'auto' }}>
      <TopBar title="Site" icon="globe"
        action={<PeriodSelector />}
      />

      <div style={{ flex: 1, padding: '20px 28px', display: 'flex', flexDirection: 'column', gap: 18 }}>

        {/* KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          <CardKPI label="Views no período"   value={loading ? '…' : totalViews.toLocaleString('pt-BR')}    icon="eye" />
          <CardKPI label="Posts visitados"    value={loading ? '…' : posts.length.toLocaleString('pt-BR')}  icon="file-text" />
          <CardKPI label="Post mais lido"     value={loading || !postMaisLido ? '—' : (postMaisLido.titulo || postMaisLido.slug)} icon="trending-up" />
          <CardKPI label="Mobile"
            value={loading || !events.length ? '—' : mobilePct + '%'}
            sub={loading || !events.length ? '' : `Desktop ${desktopPct}%`}
            icon="smartphone" />
        </div>

        {/* Linha inferior: tabela + breakdowns */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 16, alignItems: 'start' }}>

          {/* Tabela de posts */}
          <SectionCard title={`Posts (${posts.length})`} icon="bar-chart-2"
            action={
              <div style={{ display: 'flex', gap: 5 }}>
                {[['views','Mais visto'],['recente','Recente'],['alfa','A–Z']].map(([id, lbl]) => (
                  <button key={id} onClick={() => setSortBy(id)}
                    style={{ padding: '4px 10px', borderRadius: 6, cursor: 'pointer',
                      fontSize: 10.5, fontFamily: 'Roboto,sans-serif', fontWeight: 600,
                      letterSpacing: '0.03em', border: '1px solid',
                      background: sortBy === id ? 'rgba(234,170,65,.12)' : 'transparent',
                      borderColor: sortBy === id ? 'rgba(234,170,65,.3)' : 'rgba(255,255,255,.1)',
                      color: sortBy === id ? 'var(--fmn-gold)' : 'rgba(255,255,255,.35)',
                      transition: 'all 150ms' }}>
                    {lbl}
                  </button>
                ))}
              </div>
            }>

            {loading ? (
              <div style={{ textAlign: 'center', padding: '36px 0',
                color: 'rgba(255,255,255,.3)', fontSize: 13, fontFamily: 'Roboto,sans-serif' }}>
                Carregando...
              </div>
            ) : posts.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '36px 0',
                color: 'rgba(255,255,255,.3)', fontSize: 13, fontFamily: 'Roboto,sans-serif', lineHeight: 1.6 }}>
                Nenhuma visita neste período.<br/>
                <span style={{ fontSize: 12 }}>Tente "Máximo" para ver o histórico completo.</span>
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                {/* Header */}
                <div style={{
                  display: 'grid', gridTemplateColumns: '1fr 70px 120px 32px',
                  gap: 10, padding: '6px 10px', marginBottom: 4,
                  fontSize: 10, fontFamily: 'Roboto,sans-serif', fontWeight: 700,
                  letterSpacing: '0.07em', textTransform: 'uppercase',
                  color: 'rgba(255,255,255,.28)', borderBottom: '1px solid rgba(255,255,255,.05)',
                }}>
                  <span>Post</span>
                  <span style={{ textAlign: 'right' }}>Views</span>
                  <span style={{ textAlign: 'right' }}>Última visita</span>
                  <span />
                </div>

                {sorted.map((p, i) => {
                  const pct = maxViews ? Math.round(((p.views || 0) / maxViews) * 100) : 0;
                  const url = `https://www.fotografiaeomeunegocio.com.br/post.html?slug=${encodeURIComponent(p.slug)}`;
                  return (
                    <div key={p.slug}
                      style={{
                        display: 'grid', gridTemplateColumns: '1fr 70px 120px 32px',
                        gap: 10, padding: '9px 10px', borderRadius: 7, alignItems: 'center',
                        background: i % 2 === 0 ? 'rgba(255,255,255,.02)' : 'transparent',
                        transition: 'background 100ms',
                      }}
                      onMouseEnter={e => e.currentTarget.style.background = 'rgba(234,170,65,.055)'}
                      onMouseLeave={e => e.currentTarget.style.background = i % 2 === 0 ? 'rgba(255,255,255,.02)' : 'transparent'}
                    >
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 12.5, fontFamily: 'Roboto,sans-serif', fontWeight: 500,
                          color: 'rgba(255,255,255,.82)', whiteSpace: 'nowrap',
                          overflow: 'hidden', textOverflow: 'ellipsis', marginBottom: 4 }}>
                          {p.titulo || p.slug}
                        </div>
                        <Bar pct={pct} />
                      </div>
                      <div style={{ fontSize: 14, fontFamily: 'Roboto,sans-serif', fontWeight: 700,
                        color: 'var(--fmn-gold)', textAlign: 'right' }}>
                        {(p.views || 0).toLocaleString('pt-BR')}
                      </div>
                      <div style={{ fontSize: 11.5, fontFamily: 'Roboto,sans-serif',
                        color: 'rgba(255,255,255,.38)', textAlign: 'right' }}>
                        {fmtDate(p.last_view_at)}
                      </div>
                      <a href={url} target="_blank" rel="noopener" title="Abrir post"
                        style={{ display: 'flex', alignItems: 'center', justifyContent: 'center',
                          width: 26, height: 26, borderRadius: 6,
                          background: 'rgba(255,255,255,.04)', border: '1px solid rgba(255,255,255,.09)',
                          color: 'rgba(255,255,255,.35)', textDecoration: 'none', transition: 'all 150ms' }}
                        onMouseEnter={e => { e.currentTarget.style.background = 'rgba(234,170,65,.12)'; e.currentTarget.style.color = 'var(--fmn-gold)'; }}
                        onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,.04)'; e.currentTarget.style.color = 'rgba(255,255,255,.35)'; }}
                      >
                        <LucideIcon icon="external-link" size={12} />
                      </a>
                    </div>
                  );
                })}
              </div>
            )}
          </SectionCard>

          {/* Coluna lateral: breakdowns */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>

            {/* Device */}
            <SectionCard title="Dispositivo" icon="smartphone">
              {!events.length ? (
                <div style={{ fontSize: 12, color: 'rgba(255,255,255,.3)', fontFamily: 'Roboto,sans-serif',
                  textAlign: 'center', padding: '16px 0' }}>
                  {periodo === 'maximo' ? 'Disponível ao filtrar por período' : 'Sem dados'}
                </div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  {[['mobile','Celular',mobilePct,'#60a5fa'],['desktop','Desktop',desktopPct,'#a78bfa']].map(([id,lbl,pct,color]) => (
                    <div key={id}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 5 }}>
                        <span style={{ fontSize: 12, fontFamily: 'Roboto,sans-serif', color: 'rgba(255,255,255,.6)' }}>{lbl}</span>
                        <span style={{ fontSize: 12, fontFamily: 'Roboto,sans-serif', fontWeight: 700, color }}>{pct}%</span>
                      </div>
                      <Bar pct={pct} color={color} />
                    </div>
                  ))}
                </div>
              )}
            </SectionCard>

            {/* Origens */}
            <SectionCard title="De onde vieram" icon="send">
              {!events.length ? (
                <div style={{ fontSize: 12, color: 'rgba(255,255,255,.3)', fontFamily: 'Roboto,sans-serif',
                  textAlign: 'center', padding: '16px 0' }}>
                  {periodo === 'maximo' ? 'Disponível ao filtrar por período' : 'Sem dados'}
                </div>
              ) : topRefs.length === 0 ? (
                <div style={{ fontSize: 12, color: 'rgba(255,255,255,.3)', fontFamily: 'Roboto,sans-serif',
                  textAlign: 'center', padding: '16px 0' }}>Sem dados</div>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {topRefs.map(([label, count]) => {
                    const pct = Math.round((count / (events.length || 1)) * 100);
                    return (
                      <div key={label}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                          <span style={{ fontSize: 11.5, fontFamily: 'Roboto,sans-serif',
                            color: 'rgba(255,255,255,.62)', overflow: 'hidden', textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap', maxWidth: '70%' }}>{label}</span>
                          <span style={{ fontSize: 11.5, fontFamily: 'Roboto,sans-serif',
                            fontWeight: 700, color: 'rgba(255,255,255,.5)', flexShrink: 0 }}>
                            {count} <span style={{ color: 'rgba(255,255,255,.28)', fontWeight: 400 }}>({pct}%)</span>
                          </span>
                        </div>
                        <Bar pct={pct} color="rgba(234,170,65,.55)" />
                      </div>
                    );
                  })}
                </div>
              )}
            </SectionCard>

            {/* UTM */}
            {topUtms.length > 0 && (
              <SectionCard title="Campanhas UTM" icon="tag">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
                  {topUtms.map(([key, count]) => (
                    <div key={key} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontSize: 11.5, fontFamily: 'Roboto,sans-serif',
                        color: 'rgba(255,255,255,.58)', overflow: 'hidden', textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap', maxWidth: '76%' }}>{key}</span>
                      <span style={{ fontSize: 12, fontFamily: 'Roboto,sans-serif',
                        fontWeight: 700, color: 'var(--fmn-gold)', flexShrink: 0 }}>
                        {count}
                      </span>
                    </div>
                  ))}
                </div>
              </SectionCard>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SiteScreen });
