// trf-tab.jsx — Traffic & Channels top-level shell
function trfMergeLiveData(live) {
  if (!live || !live.data) return;
  const data = live.data;

  if (data.snapshot?.default) {
    Object.keys(data.snapshot.default).forEach((key) => {
      window.TRF.snapshot.default[key] = {
        ...(window.TRF.snapshot.default[key] || {}),
        ...data.snapshot.default[key],
      };
    });
  }
  if (Array.isArray(data.channels) && data.channels.length) {
    const mockByName = new Map((window.TRF.channels || []).map((row) => [row.ch, row]));
    window.TRF.channels = data.channels.map((row) => ({
      ...(mockByName.get(row.ch) || {}),
      ...row,
      cr: row.cr ?? null,
      rev: row.rev ?? null,
    }));
  }
  if (Array.isArray(data.channelMix) && data.channelMix.length) window.TRF.channelMix = data.channelMix;
  if (Array.isArray(data.pages) && data.pages.length) {
    const mockByUrl = new Map((window.TRF.pages || []).map((row) => [row.url, row]));
    window.TRF.pages = data.pages.map((row) => ({
      ...(mockByUrl.get(row.url) || {}),
      ...row,
      cr: row.cr ?? null,
    }));
  }
  if (Array.isArray(data.devices) && data.devices.length) window.TRF.devices = data.devices;
  if (Array.isArray(data.browsers) && data.browsers.length) window.TRF.browsers = data.browsers;
  if (data.seoKpi) window.TRF.seoKpi = { ...window.TRF.seoKpi, ...data.seoKpi };
  if (Array.isArray(data.seoQueries) && data.seoQueries.length) window.TRF.seoQueries = data.seoQueries;
  if (data.seoMovers) window.TRF.seoMovers = data.seoMovers;
  if (Array.isArray(data.seoLanding) && data.seoLanding.length) window.TRF.seoLanding = data.seoLanding;
  if (data.coverage?.breakdown?.length) window.TRF.coverage = data.coverage;
  if (data.cwv) window.TRF.cwv = data.cwv;
  if (Array.isArray(data.cwvByDevice) && data.cwvByDevice.length) window.TRF.cwvByDevice = data.cwvByDevice;
  if (Array.isArray(data.slowPages) && data.slowPages.length) window.TRF.slowPages = data.slowPages;
}

function trfIsoDate(offsetDays) {
  const d = new Date();
  d.setDate(d.getDate() + offsetDays);
  return d.toISOString().slice(0, 10);
}

function TrafficTab({ state, lang }) {
  const T = window.TRF_T[lang];
  const subTabs = [
    { id: 'snapshot', label: T.sec1 },
    { id: 'channels', label: T.sec2 },
    { id: 'pages',    label: T.sec3 },
    { id: 'seo',      label: T.sec4 },
    { id: 'tech',     label: T.sec5 },
  ];
  const [active, setActive] = React.useState('snapshot');
  const [startDate, setStartDate] = React.useState(() => trfIsoDate(-29));
  const [endDate, setEndDate] = React.useState(() => trfIsoDate(0));
  const [appliedRange, setAppliedRange] = React.useState(() => ({ start: trfIsoDate(-29), end: trfIsoDate(0) }));
  const [liveState, setLiveState] = React.useState({ loading: true, ga4: false, searchConsole: false, urlInspection: false, pageSpeed: false, error: null, range: null });
  const skeleton = state === 'skeleton';

  React.useEffect(() => {
    let cancelled = false;
    setLiveState((prev) => ({ ...prev, loading: true, error: null }));
    const qs = new URLSearchParams({ start: appliedRange.start, end: appliedRange.end });
    fetch(`/api/integrations/traffic?${qs.toString()}`)
      .then((res) => res.ok ? res.json() : Promise.reject(new Error(`Traffic API ${res.status}`)))
      .then((payload) => {
        if (cancelled) return;
        trfMergeLiveData(payload);
        setLiveState({
          loading: false,
          ga4: !!payload.sources?.ga4,
          searchConsole: !!payload.sources?.searchConsole,
          urlInspection: !!payload.sources?.urlInspection,
          pageSpeed: !!payload.sources?.pageSpeed,
          range: payload.range || null,
          error: payload.ok ? null : 'mock',
        });
      })
      .catch((error) => {
        if (cancelled) return;
        console.warn('Traffic live data unavailable, using mock data', error);
        setLiveState({ loading: false, ga4: false, searchConsole: false, urlInspection: false, pageSpeed: false, range: null, error: 'mock' });
      });
    return () => { cancelled = true; };
  }, [appliedRange.start, appliedRange.end]);

  const liveLabel = liveState.loading
    ? 'Loading live data...'
    : liveState.ga4 || liveState.searchConsole || liveState.urlInspection || liveState.pageSpeed
      ? [
          liveState.ga4 ? 'GA4 live' : null,
          liveState.searchConsole ? 'Search Console live' : null,
          liveState.urlInspection ? 'URL Inspection live' : null,
          liveState.pageSpeed ? 'PageSpeed live' : null,
        ].filter(Boolean).join(' · ')
      : 'Mock fallback';
  const canApply = startDate && endDate && (startDate !== appliedRange.start || endDate !== appliedRange.end);

  return (
    <div className="page rev-page trf-page">
      <div className="rev-page-head">
        <div className="rev-page-title-row">
          <div>
            <h1 className="rev-page-title">{T.pageTitle}</h1>
            <div className="rev-page-sub">{T.pageSub} · {liveState.range ? `${liveState.range.startDate} — ${liveState.range.endDate}` : `${appliedRange.start} — ${appliedRange.end}`}</div>
          </div>
          <div className="trf-head-tools">
            <div className="trf-date-range">
              <input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} />
              <span>—</span>
              <input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} />
              <button disabled={!canApply || liveState.loading} onClick={() => setAppliedRange({ start: startDate, end: endDate })}>
                Apply
              </button>
            </div>
            <div className={`trf-live-badge ${liveState.ga4 || liveState.searchConsole || liveState.urlInspection || liveState.pageSpeed ? 'on' : liveState.loading ? 'loading' : 'mock'}`}>
              <span></span>{liveLabel}
            </div>
          </div>
        </div>
        <div className="rev-subtabs">
          {subTabs.map(st => (
            <button key={st.id} className={`rev-subtab ${active === st.id ? 'on' : ''}`} onClick={() => setActive(st.id)}>
              {st.label}
            </button>
          ))}
        </div>
      </div>

      {skeleton ? (
        <div className="trf-skel">
          {[1, 2, 3, 4, 5, 6].map(i => <div key={i} className="trf-skel-card" />)}
        </div>
      ) : (
        <>
          {active === 'snapshot' && <window.TrfSnapshot state={state} lang={lang} />}
          {active === 'channels' && <window.TrfChannels lang={lang} />}
          {active === 'pages' && <window.TrfPages lang={lang} />}
          {active === 'seo' && <window.TrfSeo lang={lang} />}
          {active === 'tech' && <window.TrfTech lang={lang} />}
        </>
      )}
    </div>
  );
}

window.TrafficTab = TrafficTab;
