// campaign-report.jsx — rapoartele de campanie, pentru brand si pentru uz intern.
//
// De ce nu generam un fisier PDF cu o biblioteca: bibliotecile de PDF din browser
// (jsPDF, html2canvas) transforma pagina in imagine — textul nu se mai poate selecta,
// diacriticele se strica, iar fisierul iese de cateva MB. Browserul stie deja sa faca
// PDF-uri bune din pagini: Printeaza -> "Salveaza ca PDF". Asa iese text adevarat,
// se cauta in el, e mic, si arata la fel pe orice calculator.
//
// Raportul se deseneaza intr-un portal lipit direct de <body>, ca sa putem ascunde
// restul paginii la printare cu o singura regula CSS.
//
// Expune:
//   window.CampaignReport({ campaign, brand, creators, influencers, staffList, onlyCreatorId, onClose })

const { useState: useStateCR, useEffect: useEffectCR } = React;

function _n(v) { return (v == null || v === '') ? 0 : (Number(v) || 0); }
function _fmt(v) {
  if (v == null || v === '' || Number.isNaN(Number(v))) return '—';
  return Number(v).toLocaleString('ro-RO');
}
function _date(d) {
  if (!d) return '—';
  const x = new Date(d.length === 10 ? d + 'T00:00:00' : d);
  return isNaN(x.getTime()) ? '—' : x.toLocaleDateString('ro-RO');
}

// Suma unui camp peste o lista, dar null cand nimeni nu a completat nimic.
// "0 views" si "nu stim cate views" sunt lucruri diferite intr-un raport catre brand.
function _sum(rows, field) {
  const withValue = rows.filter(r => r[field] != null && r[field] !== '');
  if (withValue.length === 0) return null;
  return withValue.reduce((acc, r) => acc + _n(r[field]), 0);
}

function CampaignReport({ campaign, brand, creators, influencers, staffList, onlyCreatorId, onClose }) {
  const [videos, setVideos] = useStateCR([]);
  const [lives, setLives] = useStateCR([]);
  const [loading, setLoading] = useStateCR(true);

  const shown = onlyCreatorId ? creators.filter(c => c.id === onlyCreatorId) : creators;
  const shownIds = shown.map(c => c.id);

  useEffectCR(() => {
    (async () => {
      if (shownIds.length === 0) { setLoading(false); return; }
      const [{ data: v }, { data: l }] = await Promise.all([
        window.sb.from('campaign_creator_videos').select('*').in('campaign_creator_id', shownIds).order('position'),
        window.sb.from('campaign_creator_lives').select('*').in('campaign_creator_id', shownIds).order('position'),
      ]);
      setVideos(v || []);
      setLives(l || []);
      setLoading(false);
    })();
  }, [campaign.id, onlyCreatorId]);

  const videosOf = (ccId) => videos.filter(v => v.campaign_creator_id === ccId);
  const livesOf = (ccId) => lives.filter(l => l.campaign_creator_id === ccId);
  const infOf = (ccId) => {
    const cc = creators.find(c => c.id === ccId);
    return cc ? influencers.find(i => i.id === cc.influencer_id) : null;
  };

  const isSingle = !!onlyCreatorId;
  const title = isSingle ? 'Raport creator' : 'Raport campanie';

  // Totalurile se aduna din randuri, niciodata scrise de mana — altfel raportul
  // catre brand ar putea spune altceva decat datele din panou.
  const totals = {
    creatori: shown.length,
    videoclipuri: videos.length,
    publicate: videos.filter(v => v.status === 'Publicat').length,
    views: _sum(videos, 'views'),
    likeVideo: _sum(videos, 'likes'),
    comVideo: _sum(videos, 'comments'),
    liveuri: lives.length,
    spectatori: _sum(lives, 'viewers_peak'),
    laMentiune: _sum(lives, 'viewers_at_mention'),
    minuteLive: _sum(lives, 'duration_minutes'),
    likeLive: _sum(lives, 'likes'),
    comLive: _sum(lives, 'comments'),
  };

  const manager = staffList.find(s => s.id === campaign.assigned_to);
  const contact = staffList.find(s => s.id === campaign.brand_contact);
  const brandName = brand ? (brand.brand || brand.company) : '—';

  const handlePrint = () => window.print();

  const statCards = [
    { label: 'Creatori', value: totals.creatori },
    { label: 'Videoclipuri publicate', value: totals.publicate + ' din ' + totals.videoclipuri },
    { label: 'Vizualizări totale', value: _fmt(totals.views) },
    { label: 'Live-uri', value: totals.liveuri },
    { label: 'Spectatori în live', value: _fmt(totals.spectatori) },
    { label: 'Spectatori la mențiune', value: _fmt(totals.laMentiune) },
  ];

  return ReactDOM.createPortal(
    <div className="report-print-root" style={{
      position: 'fixed', inset: 0, zIndex: 400, overflowY: 'auto',
      background: '#f4f4f5', padding: '24px 16px',
    }}>
      {/* Bara de comenzi — nu se printeaza */}
      <div className="report-toolbar" style={{
        position: 'sticky', top: 0, zIndex: 2, maxWidth: 920, margin: '0 auto 16px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
        padding: '12px 16px', borderRadius: 10, background: '#18181b', color: '#fff', flexWrap: 'wrap',
      }}>
        <div style={{ fontSize: 13 }}>
          {loading ? 'Se încarcă datele...' : 'Gata de printat. Alege „Salvează ca PDF" în fereastra de printare.'}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={handlePrint} disabled={loading} style={{
            padding: '8px 16px', borderRadius: 8, border: 'none', cursor: loading ? 'not-allowed' : 'pointer',
            background: '#52F20F', color: '#000', fontWeight: 600, fontSize: 13, opacity: loading ? .5 : 1,
          }}>Printează / Salvează PDF</button>
          <button onClick={onClose} style={{
            padding: '8px 16px', borderRadius: 8, border: '1px solid rgba(255,255,255,.2)',
            background: 'transparent', color: '#fff', cursor: 'pointer', fontSize: 13,
          }}>Închide</button>
        </div>
      </div>

      {/* Foaia de raport */}
      <div className="report-sheet" style={{
        maxWidth: 920, margin: '0 auto', background: '#fff', color: '#18181b',
        padding: '40px 44px', borderRadius: 10, boxShadow: '0 2px 24px rgba(0,0,0,.12)',
        fontFamily: "'Geist', system-ui, sans-serif", lineHeight: 1.55,
      }}>
        {/* Antet */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 20, borderBottom: '2px solid #18181b', paddingBottom: 16, marginBottom: 24 }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: '-.02em' }}>4U Agency</div>
            <div style={{ fontSize: 11, color: '#71717a', letterSpacing: '.08em', textTransform: 'uppercase', marginTop: 2 }}>Agenție de influencer marketing</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 11, color: '#71717a', letterSpacing: '.12em', textTransform: 'uppercase' }}>{title}</div>
            <div style={{ fontSize: 12, color: '#3f3f46', marginTop: 2 }}>Generat la {new Date().toLocaleDateString('ro-RO')}</div>
          </div>
        </div>

        <h1 style={{ fontSize: 26, margin: '0 0 6px', fontWeight: 700, letterSpacing: '-.02em' }}>{campaign.name}</h1>
        <div style={{ fontSize: 13, color: '#52525b', marginBottom: 28 }}>
          Brand: <strong style={{ color: '#18181b' }}>{brandName}</strong>
          {(campaign.start_date || campaign.end_date) && <span> · Perioadă: {_date(campaign.start_date)} – {_date(campaign.end_date)}</span>}
          {manager && <span> · Campaign manager: {manager.full_name}</span>}
          {contact && <span> · Contact: {contact.full_name}</span>}
        </div>

        {loading ? (
          <div style={{ padding: 40, textAlign: 'center', color: '#71717a' }}>Se încarcă rezultatele...</div>
        ) : (
          <React.Fragment>
            {/* Rezumat cifre */}
            <ReportSectionTitle>Rezumat</ReportSectionTitle>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 8 }}>
              {statCards.map(c => (
                <div key={c.label} style={{ border: '1px solid #e4e4e7', borderRadius: 8, padding: '12px 14px', background: '#fafafa' }}>
                  <div style={{ fontSize: 10, color: '#71717a', textTransform: 'uppercase', letterSpacing: '.06em' }}>{c.label}</div>
                  <div style={{ fontSize: 20, fontWeight: 700, marginTop: 4 }}>{c.value}</div>
                </div>
              ))}
            </div>
            <div style={{ fontSize: 12, color: '#52525b', marginBottom: 28 }}>
              Interacțiuni: <strong>{_fmt(totals.likeVideo == null && totals.likeLive == null ? null : _n(totals.likeVideo) + _n(totals.likeLive))}</strong> like-uri
              {' · '}<strong>{_fmt(totals.comVideo == null && totals.comLive == null ? null : _n(totals.comVideo) + _n(totals.comLive))}</strong> comentarii
              {totals.minuteLive != null && <span> · <strong>{_fmt(totals.minuteLive)}</strong> minute de live</span>}
            </div>

            {/* Ce am promis si ce a iesit */}
            {!isSingle && (campaign.kpi_agreed || campaign.results_summary || campaign.results_business || campaign.results_brand_feedback) && (
              <React.Fragment>
                <ReportSectionTitle>Obiective și concluzii</ReportSectionTitle>
                <div style={{ marginBottom: 28 }}>
                  <ReportField label="KPI agreat" value={campaign.kpi_agreed} />
                  <ReportField label="Concluzia campaniei" value={campaign.results_summary} />
                  <ReportField label="Rezultate de business" value={campaign.results_business} />
                  <ReportField label="Feedback de la brand" value={campaign.results_brand_feedback} />
                </div>
              </React.Fragment>
            )}

            {/* Creatorii */}
            <ReportSectionTitle>{isSingle ? 'Rezultate' : 'Rezultate pe creator'}</ReportSectionTitle>
            {shown.length === 0 ? (
              <div style={{ fontSize: 13, color: '#71717a' }}>Niciun creator alocat pe campanie.</div>
            ) : shown.map(cc => {
              const inf = infOf(cc.id);
              const vs = videosOf(cc.id);
              const ls = livesOf(cc.id);
              const subViews = _sum(vs, 'views');
              return (
                <div key={cc.id} className="report-creator" style={{ border: '1px solid #e4e4e7', borderRadius: 8, padding: 16, marginBottom: 14 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, flexWrap: 'wrap', marginBottom: 4 }}>
                    <div style={{ fontSize: 15, fontWeight: 700 }}>
                      {inf ? inf.full_name : 'Creator șters'}
                      {inf && inf.tiktok_handle && <span style={{ fontWeight: 400, color: '#52525b', marginLeft: 8 }}>@{inf.tiktok_handle}</span>}
                    </div>
                    {inf && inf.tiktok_followers != null && (
                      <div style={{ fontSize: 12, color: '#52525b' }}>{_fmt(inf.tiktok_followers)} followers TikTok</div>
                    )}
                  </div>

                  {cc.deliverables && <div style={{ fontSize: 12, color: '#52525b', marginBottom: 10 }}>Livrabile: {cc.deliverables}</div>}

                  {vs.length > 0 && (
                    <ReportTable
                      head={['#', 'Status', 'Views', 'Like-uri', 'Comentarii', 'Link']}
                      rows={vs.map((v, i) => [
                        String(i + 1), v.status, _fmt(v.views), _fmt(v.likes), _fmt(v.comments),
                        v.published_url ? <a href={v.published_url} style={{ color: '#166534' }}>postare</a> : '—',
                      ])}
                    />
                  )}

                  {ls.length > 0 && (
                    <ReportTable
                      head={['#', 'Data', 'Durată', 'Spectatori', 'La mențiune', 'Like-uri', 'Comentarii']}
                      rows={ls.map((l, i) => [
                        String(i + 1), _date(l.live_date),
                        l.duration_minutes != null ? l.duration_minutes + ' min' : '—',
                        _fmt(l.viewers_peak), _fmt(l.viewers_at_mention), _fmt(l.likes), _fmt(l.comments),
                      ])}
                    />
                  )}

                  {vs.length === 0 && ls.length === 0 && (
                    <div style={{ fontSize: 12, color: '#a1a1aa', fontStyle: 'italic' }}>Niciun livrabil trecut încă.</div>
                  )}

                  {(vs.length > 0 || ls.length > 0) && (
                    <div style={{ fontSize: 12, color: '#3f3f46', marginTop: 8, paddingTop: 8, borderTop: '1px dashed #e4e4e7' }}>
                      Total: <strong>{_fmt(subViews)}</strong> views
                      {ls.length > 0 && <span> · <strong>{ls.length}</strong> {ls.length === 1 ? 'live' : 'live-uri'}</span>}
                    </div>
                  )}
                </div>
              );
            })}

            <div style={{ marginTop: 28, paddingTop: 14, borderTop: '1px solid #e4e4e7', fontSize: 11, color: '#71717a' }}>
              Raport generat automat din panoul intern 4U Agency. Cifrele reflectă datele înregistrate la data generării.
            </div>
          </React.Fragment>
        )}
      </div>
    </div>,
    document.body
  );
}

function ReportSectionTitle({ children }) {
  return (
    <h2 style={{
      fontSize: 11, letterSpacing: '.14em', textTransform: 'uppercase', color: '#71717a',
      margin: '0 0 12px', fontWeight: 600,
    }}>{children}</h2>
  );
}

function ReportField({ label, value }) {
  if (!value) return null;
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ fontSize: 11, color: '#71717a', textTransform: 'uppercase', letterSpacing: '.06em', marginBottom: 2 }}>{label}</div>
      <div style={{ fontSize: 13, whiteSpace: 'pre-wrap' }}>{value}</div>
    </div>
  );
}

function ReportTable({ head, rows }) {
  return (
    <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 8 }}>
      <thead>
        <tr>
          {head.map(h => (
            <th key={h} style={{ textAlign: 'left', padding: '6px 8px', background: '#fafafa', borderBottom: '1px solid #e4e4e7', fontWeight: 600, color: '#3f3f46', fontSize: 11 }}>{h}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {rows.map((r, i) => (
          <tr key={i}>
            {r.map((cell, j) => (
              <td key={j} style={{ padding: '6px 8px', borderBottom: '1px solid #f4f4f5' }}>{cell}</td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

window.CampaignReport = CampaignReport;
