/* Admin: connect a lead's GA4 and Shopify, pull the AI-referred numbers.

   The token field is a password field, is sent once, and never comes
   back from the server: the status shows only the store and the last four
   characters. */

function AttributionPanel({ slug, token, report, onExpired, onReportChanged }) {
  const [st, setSt] = React.useState(null);
  const [busy, setBusy] = React.useState('');
  const [flash, setFlash] = React.useState('');
  const [propertyId, setPropertyId] = React.useState('');
  const [shop, setShop] = React.useState('');
  const [shopToken, setShopToken] = React.useState('');
  const [days, setDays] = React.useState(90);
  const [open, setOpen] = React.useState(false);

  const call = React.useCallback(async (action, extra) => {
    const d = await apiCall('/api/attribution', { method: 'POST', headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
      body: JSON.stringify({ action, slug, ...(extra || {}) }) });
    if (d.status === 401) { onExpired(); throw new Error('expired'); }
    return d;
  }, [slug, token]);

  React.useEffect(() => { call('status').then((d) => setSt(d.ok ? d : { off: d.error === 'feature-off', message: d.message })).catch(() => {}); }, [call]);

  const act = async (action, extra, after) => {
    setBusy(action); setFlash('');
    try {
      const d = await call(action, extra);
      if (!d.ok) setFlash(d.message || d.detail || `${action} failed (HTTP ${d.status}).`);
      else { if (d.connections) setSt((s) => ({ ...s, ...d })); if (after) after(d); onReportChanged(); }
    } catch (e) { setFlash('Could not reach the server.'); }
    setBusy('');
  };

  if (!st) return <Panel title="AI traffic"><div style={{ color: 'var(--fg-subtle)', fontSize: 13 }}>Loading…</div></Panel>;
  if (st.off) return null;
  const c = st.connections || {};
  const ins = st.instructions || {};
  const a = report.attribution;
  return (
    <Panel title={`AI traffic · ${c.ga4 ? 'GA4 connected' : 'GA4 not connected'} · ${c.shopify ? 'Shopify connected' : 'Shopify not connected'}`} tone={c.ga4 || c.shopify ? 'good' : undefined}>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', fontSize: 13, color: 'var(--fg-muted)' }}>
        <span>{a && a.series ? `Numbers pulled ${String(a.computed_at).slice(0, 16).replace('T', ' ')} (${a.days} days): ${a.totals.sessions} AI-referred sessions, ${a.totals.orders} orders.` : 'Numbers not pulled yet.'}</span>
        {!st.key_present && <span style={{ color: 'var(--crit)' }}>LOJO_CRED_KEY is not set: credentials cannot be stored.</span>}
        <button style={smallBtn()} onClick={() => setOpen((o) => !o)}>{open ? 'Hide connections' : 'Connections'}</button>
        {(c.ga4 || c.shopify) &&
        <React.Fragment>
          <label style={{ display: 'flex', gap: 6, alignItems: 'center' }}>days
            <input type="number" min={7} max={365} value={days} onChange={(e) => setDays(Number(e.target.value) || 90)} style={{ ...tinyInput, width: 70 }} />
          </label>
          <button style={smallBtn('accent')} disabled={!!busy} onClick={() => act('metrics', { days })}>{busy === 'metrics' ? 'Pulling…' : 'Pull the numbers'}</button>
        </React.Fragment>}
      </div>
      {flash && <div style={{ marginTop: 10, fontSize: 13.5, color: 'var(--warn)' }}>{flash}</div>}
      {open &&
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: 14, marginTop: 14 }}>
        <div style={{ padding: '12px 14px', borderRadius: 'var(--r-md)', background: 'var(--navy)', border: '1px solid var(--line)' }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Google Analytics 4</div>
          {c.ga4
            ? <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                Property <span className="mono">{c.ga4.property_id}</span>, connected {String(c.ga4.connected_at).slice(0, 10)}.
                {(c.ga4.top_pages || []).length > 0 && <div>Most visited: {c.ga4.top_pages.slice(0, 5).map((p) => p.path).join(', ')} — read first on the next scan.</div>}
                <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
                  <button style={smallBtn()} disabled={!!busy} onClick={() => act('pages')}>Refresh page list</button>
                  <button style={smallBtn('crit')} disabled={!!busy} onClick={() => { if (window.confirm('Disconnect GA4? The stored property id is deleted.')) act('disconnect', { which: 'ga4' }); }}>Disconnect</button>
                </div>
              </div>
            : <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                <ol style={{ margin: '0 0 8px 18px', padding: 0 }}>{(ins.ga4 && ins.ga4.steps || []).map((s, i) => <li key={i}>{s}</li>)}</ol>
                {ins.ga4 && ins.ga4.service_account_email && <div style={{ marginBottom: 8, display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}><span className="mono" style={{ fontSize: 12 }}>{ins.ga4.service_account_email}</span><CopyButton text={ins.ga4.service_account_email} label="Copy email" /></div>}
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <input value={propertyId} onChange={(e) => setPropertyId(e.target.value)} placeholder="GA4 property ID (numbers)" style={{ ...tinyInput, width: 220 }} />
                  <button style={smallBtn('accent')} disabled={!!busy || !propertyId.trim() || !st.ga4_ready} onClick={() => act('connect-ga4', { property_id: propertyId.trim() }, () => setPropertyId(''))}>{busy === 'connect-ga4' ? 'Checking…' : 'Connect GA4'}</button>
                </div>
                {!st.ga4_ready && <div style={{ color: 'var(--crit)', marginTop: 6 }}>GA4_SERVICE_ACCOUNT_JSON is not set on the server.</div>}
              </div>}
        </div>
        <div style={{ padding: '12px 14px', borderRadius: 'var(--r-md)', background: 'var(--navy)', border: '1px solid var(--line)' }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 6 }}>Shopify</div>
          {c.shopify
            ? <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                <span className="mono">{c.shopify.shop}</span>{c.shopify.name ? ` (${c.shopify.name})` : ''}, token ending <span className="mono">{c.shopify.token_tail}</span>, connected {String(c.shopify.connected_at).slice(0, 10)}. Read-only orders.
                <div style={{ marginTop: 8 }}><button style={smallBtn('crit')} disabled={!!busy} onClick={() => { if (window.confirm('Disconnect Shopify? The stored token is deleted.')) act('disconnect', { which: 'shopify' }); }}>Disconnect</button></div>
              </div>
            : <div style={{ fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.6 }}>
                <ol style={{ margin: '0 0 8px 18px', padding: 0 }}>{(ins.shopify && ins.shopify.steps || []).map((s, i) => <li key={i}>{s}</li>)}</ol>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <input value={shop} onChange={(e) => setShop(e.target.value)} placeholder="store.myshopify.com" style={{ ...tinyInput, width: 200 }} />
                  <input type="password" value={shopToken} onChange={(e) => setShopToken(e.target.value)} placeholder="Admin API access token" autoComplete="off" style={{ ...tinyInput, width: 220 }} />
                  <button style={smallBtn('accent')} disabled={!!busy || !shop.trim() || !shopToken.trim()} onClick={() => act('connect-shopify', { shop: shop.trim(), token: shopToken.trim() }, () => { setShop(''); setShopToken(''); })}>{busy === 'connect-shopify' ? 'Checking…' : 'Connect Shopify'}</button>
                </div>
              </div>}
        </div>
      </div>}
    </Panel>);
}
