// B2B schvaľovanie, Individuálne ceny, AI chat s odpoveďou, Integrácie, Launcher

function daysSince(dateStr) {
  if (!dateStr) return null;
  const d = new Date(dateStr.replace(' ', 'T'));
  if (isNaN(d)) return null;
  return Math.floor((Date.now() - d.getTime()) / 86400000);
}

function B2BDenyModal({ request, onClose, onDone, notify }) {
  const [note, setNote] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  async function submit() {
    setBusy(true);
    const r = await API.decideB2B(request.id, 'deny', note);
    setBusy(false);
    if (r.ok) { notify('success', 'Žiadosť zamietnutá.'); onDone(); onClose(); }
    else      { notify('error', r.body.message || 'Nepodarilo sa uložiť.'); }
  }
  return (
    <Modal
      title={`Zamietnuť žiadosť — ${request.company_name || request.email}`}
      onClose={onClose}
      width={480}
      footer={
        <>
          <button className="btn" onClick={onClose} disabled={busy}>Zrušiť</button>
          <button className="btn btn-danger" onClick={submit} disabled={busy}>
            {busy ? 'Ukladám…' : 'Zamietnuť'}
          </button>
        </>
      }
    >
      <div className="field">
        <label>Dôvod (viditeľný pre zákazníka v notifikácii)</label>
        <textarea className="textarea" value={note} onChange={e => setNote(e.target.value)} rows={4} placeholder="Napr. Nesprávne IČO, Nepripojené dokumenty, …"/>
      </div>
      <div className="small muted" style={{marginTop:6}}>Žiadateľovi sa nastaví status <b>denied</b>. Zostáva zaregistrovaný ako B2C (bez B2B cien).</div>
    </Modal>
  );
}

function B2BApprovals() {
  const [list, setList] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const [busyId, setBusyId] = React.useState(null);
  const [denying, setDenying] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const canEdit = window.hasPerm ? window.hasPerm('b2b.edit') : false;

  async function reload() {
    setLoading(true);
    const r = await API.listB2BPending();
    setLoading(false);
    if (r.status === 503) { setError('not_configured'); return; }
    if (r.status === 404 || r.body.error === 'bridge_not_installed') { setError('bridge_missing'); return; }
    if (!r.ok)  { setError(r.body.message || 'Chyba.'); return; }
    setError(null);
    setList(r.body.pending || []);
  }
  React.useEffect(() => { reload(); }, []);

  async function approve(req) {
    if (!canEdit) return;
    if (!confirm(`Schváliť B2B žiadosť pre ${req.company_name || req.email}?\n\nNastaví sa status approved + rola firemny_zakaznik.`)) return;
    setBusyId(req.id);
    const r = await API.decideB2B(req.id, 'approve');
    setBusyId(null);
    if (r.ok) { setToast({ kind: 'success', text: `Schválené: ${req.company_name || req.email}` }); reload(); }
    else      { setToast({ kind: 'error',   text: r.body.message || 'Nepodarilo sa schváliť.' }); }
  }

  if (error === 'not_configured') {
    return (
      <AppShell active="b2b" crumbs={['CRM','B2B schvaľovanie']}>
        <div className="page-head"><div><h1>B2B schvaľovanie</h1></div></div>
        <NotConnected integration="WordPress" message="Pre B2B schvaľovanie pripojte WordPress."/>
      </AppShell>
    );
  }
  if (error === 'bridge_missing') {
    return (
      <AppShell active="b2b" crumbs={['CRM','B2B schvaľovanie']}>
        <div className="page-head"><div><h1>B2B schvaľovanie</h1></div></div>
        <div className="card" style={{padding:24, textAlign:'center', maxWidth:560, margin:'30px auto'}}>
          <div style={{fontSize:42}}>🧩</div>
          <h3>WP bridge plugin chýba</h3>
          <p className="muted">Nahrajte <code>wp-plugin/dd-crm-bridge.php</code> do <code>wp-content/mu-plugins/</code> na WordPress server. Potom obnovte túto stránku.</p>
        </div>
      </AppShell>
    );
  }

  const filtered = list.filter(r =>
    !search ||
    (r.company_name || '').toLowerCase().includes(search.toLowerCase()) ||
    (r.email || '').toLowerCase().includes(search.toLowerCase()) ||
    (r.company_id || '').includes(search)
  );

  const urgentCount = list.filter(r => (daysSince(r.request_date) || 0) >= 3).length;

  return (
    <AppShell active="b2b" crumbs={['CRM','B2B schvaľovanie']}>
      {toast && <Toast kind={toast.kind} onClose={() => setToast(null)}>{toast.text}</Toast>}
      {denying && (
        <B2BDenyModal request={denying} onClose={() => setDenying(null)} onDone={reload} notify={(k,t) => setToast({kind:k, text:t})}/>
      )}

      <div className="page-head">
        <div>
          <h1>B2B schvaľovanie</h1>
          <p>{list.length} žiadostí čaká na schválenie{urgentCount > 0 ? ` · ${urgentCount} čaká viac ako 3 dni` : ''}</p>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={reload}><Ico.upload/>Obnoviť</button>
        </div>
      </div>

      <div className="filters">
        <div style={{position:'relative', flex:1, maxWidth:320}}>
          <Ico.search style={{position:'absolute', left:10, top:9, color:'var(--ink-400)'}}/>
          <input className="input" placeholder="Firma, IČO, e-mail…" style={{paddingLeft:30, width:'100%'}} value={search} onChange={e => setSearch(e.target.value)}/>
        </div>
      </div>

      <div className="card" style={{overflow:'hidden'}}>
        {loading && <div style={{padding:20}} className="muted">Načítavam…</div>}
        {!loading && filtered.length === 0 && (
          <div style={{padding:40, textAlign:'center', color:'var(--ink-500)'}}>
            {list.length === 0 ? '🎉 Žiadne čakajúce žiadosti.' : 'Žiadne výsledky pre tento filter.'}
          </div>
        )}
        {!loading && filtered.length > 0 && (
          <div style={{overflow:'auto'}}>
            <table className="tbl">
              <thead><tr>
                <th>Firma</th><th>IČO / IČ DPH</th><th>Kontakt</th><th>Adresa</th><th>Čaká</th><th style={{textAlign:'right'}}>Akcia</th>
              </tr></thead>
              <tbody>
                {filtered.map(r => {
                  const days = daysSince(r.request_date);
                  const urgent = (days || 0) >= 3;
                  return (
                    <tr key={r.id} style={busyId === r.id ? { opacity: 0.5 } : {}}>
                      <td>
                        <b>{r.company_name || '—'}</b>
                        <div className="small muted">User #{r.id}</div>
                      </td>
                      <td>
                        <span className="mono small">{r.company_id || '—'}</span>
                        {r.company_icdph && <div className="small muted">{r.company_icdph}</div>}
                      </td>
                      <td>
                        <div>{r.name || '—'}</div>
                        <div className="small muted">{r.email}</div>
                        {r.billing_phone && <div className="small">{r.billing_phone}</div>}
                      </td>
                      <td className="small">
                        {r.billing_address_1 || '—'}
                        {(r.billing_postcode || r.billing_city) && <div className="muted">{[r.billing_postcode, r.billing_city].filter(Boolean).join(' ')}</div>}
                        {r.billing_country && <div className="muted">{r.billing_country}</div>}
                      </td>
                      <td>
                        {urgent
                          ? <span className="chip red dot">{days} dní</span>
                          : <span className="chip amber dot">{days == null ? '—' : days + ' dni'}</span>
                        }
                      </td>
                      <td style={{textAlign:'right', whiteSpace:'nowrap'}}>
                        {canEdit && (
                          <>
                            <button
                              className="btn btn-xs"
                              style={{background:'var(--green-100)', color:'#135e37', borderColor:'transparent'}}
                              onClick={() => approve(r)}
                              disabled={busyId === r.id}
                            >
                              <Ico.check/>Schváliť
                            </button>
                            <button
                              className="btn btn-xs btn-danger"
                              style={{marginLeft:4}}
                              onClick={() => setDenying(r)}
                              disabled={busyId === r.id}
                              title="Zamietnuť"
                            >
                              <Ico.x/>
                            </button>
                          </>
                        )}
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </AppShell>
  );
}

// ─────────────────────────────────────────────
// Individual Pricing — per customer via WP bridge
// ─────────────────────────────────────────────

function IndividualPricingEditor({ userId, onBack, notify }) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [dirty, setDirty] = React.useState({});         // { product_id: new_price }
  const [toDelete, setToDelete] = React.useState([]);   // [product_id, ...]
  const [busy, setBusy] = React.useState(false);

  // Add-product search
  const [search, setSearch] = React.useState('');
  const [searchResults, setSearchResults] = React.useState([]);
  const [searching, setSearching] = React.useState(false);
  const [newPrice, setNewPrice] = React.useState('');
  const [pickedProduct, setPickedProduct] = React.useState(null);

  async function reload() {
    setLoading(true);
    const r = await API.getIndividualPrices(userId);
    setLoading(false);
    if (r.ok) { setData(r.body); setDirty({}); setToDelete([]); }
    else { notify('error', r.body.message || 'Nepodarilo sa načítať.'); onBack(); }
  }
  React.useEffect(() => { reload(); /* eslint-disable-next-line */ }, [userId]);

  React.useEffect(() => {
    if (!search || search.length < 2) { setSearchResults([]); return; }
    const id = setTimeout(async () => {
      setSearching(true);
      const r = await API.listProducts({ search, per_page: 8 });
      setSearching(false);
      if (r.ok) {
        const existing = new Set((data?.prices || []).map(p => p.product_id));
        setSearchResults((r.body.products || []).filter(p => !existing.has(p.id)));
      }
    }, 300);
    return () => clearTimeout(id);
  }, [search, data]);

  function setNew(productId, val) {
    setDirty(prev => ({ ...prev, [productId]: val }));
  }

  function markDelete(productId) {
    setToDelete(prev => prev.includes(productId) ? prev : [...prev, productId]);
    setDirty(prev => { const n = { ...prev }; delete n[productId]; return n; });
  }

  function undoDelete(productId) {
    setToDelete(prev => prev.filter(id => id !== productId));
  }

  function addProduct() {
    if (!pickedProduct) return;
    const price = parseFloat(String(newPrice).replace(',', '.'));
    if (!(price > 0)) return notify('error', 'Zadajte kladnú cenu.');
    // Add to data locally + dirty
    const row = {
      product_id: pickedProduct.id,
      product_name: pickedProduct.name,
      product_sku: pickedProduct.sku,
      regular_price: parseFloat(pickedProduct.regular_price || pickedProduct.price || 0),
      individual_price: price,
      discount_pct: null,
    };
    setData(d => ({ ...d, prices: [...(d.prices || []), row] }));
    setDirty(prev => ({ ...prev, [pickedProduct.id]: price }));
    setPickedProduct(null); setSearch(''); setSearchResults([]); setNewPrice('');
  }

  async function saveAll() {
    const prices = Object.entries(dirty).map(([product_id, individual_price]) => ({
      product_id: parseInt(product_id, 10),
      individual_price: parseFloat(String(individual_price).replace(',', '.')),
    }));
    const payload_delete = toDelete;
    if (prices.length === 0 && payload_delete.length === 0) {
      notify('info', 'Nič na uloženie.');
      return;
    }
    setBusy(true);
    const r = await API.setIndividualPrices(userId, prices, payload_delete);
    setBusy(false);
    if (r.ok) { notify('success', `Uložené · ${r.body.updated || 0} zmenených, ${r.body.deleted || 0} zmazaných.`); reload(); }
    else      { notify('error', r.body.message || 'Chyba.'); }
  }

  if (loading) {
    return <AppShell active="pricing" crumbs={['CRM','Individuálne ceny','…']}><div className="muted" style={{padding:20}}>Načítavam…</div></AppShell>;
  }
  if (!data) return null;

  const totalChanges = Object.keys(dirty).length + toDelete.length;

  return (
    <AppShell active="pricing" crumbs={['CRM','Individuálne ceny', data.name || data.email]}>
      <div className="page-head">
        <div>
          <div className="hstack" style={{marginBottom:4}}>
            <h1 style={{margin:0}}>{data.name || '(bez mena)'}</h1>
            {data.is_company && <span className="chip navy dot">B2B</span>}
          </div>
          <p>{data.email} · {data.company || '—'} · {data.count || 0} individuálnych cien</p>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={onBack}>← Späť</button>
          <button className="btn btn-primary" onClick={saveAll} disabled={busy || totalChanges === 0}>
            {busy ? 'Ukladám…' : `Uložiť (${totalChanges})`}
          </button>
        </div>
      </div>

      <div className="card" style={{padding:14, marginBottom:12}}>
        <div className="small muted" style={{textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:600, marginBottom:8}}>
          Pridať produkt do cenníka
        </div>
        {pickedProduct ? (
          <div className="hstack" style={{gap:10}}>
            <div style={{flex:1, padding:'8px 10px', background:'var(--blue-50)', borderRadius:6, border:'1px solid var(--border)'}}>
              <div style={{fontWeight:500}}>{pickedProduct.name}</div>
              <div className="small muted">{pickedProduct.sku || 'bez SKU'} · bežná cena {formatCurrency(parseFloat(pickedProduct.regular_price || pickedProduct.price || 0))}</div>
            </div>
            <div className="field" style={{width:140}}>
              <input className="input" placeholder="Nová cena €" value={newPrice} onChange={e => setNewPrice(e.target.value)} inputMode="decimal" autoFocus/>
            </div>
            <button className="btn btn-primary" onClick={addProduct} disabled={!newPrice}>Pridať</button>
            <button className="btn" onClick={() => { setPickedProduct(null); setSearch(''); setNewPrice(''); }}>Zrušiť</button>
          </div>
        ) : (
          <div>
            <input className="input" placeholder="Hľadať produkt (SKU alebo názov, min. 2 znaky)" value={search} onChange={e => setSearch(e.target.value)} style={{width:'100%'}}/>
            {searching && <div className="small muted" style={{marginTop:4}}>Hľadám…</div>}
            {searchResults.length > 0 && (
              <div style={{maxHeight:180, overflow:'auto', border:'1px solid var(--border)', borderRadius:6, marginTop:6}}>
                {searchResults.map(p => (
                  <div key={p.id} onClick={() => setPickedProduct(p)} style={{padding:'8px 10px', cursor:'pointer', borderBottom:'1px solid var(--border)', fontSize:12.5}}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--blue-50)'}
                    onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                    <div style={{fontWeight:500}}>{p.name}</div>
                    <div className="small muted">{p.sku || 'bez SKU'} · bežná {formatCurrency(parseFloat(p.regular_price || p.price || 0))}</div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      <div className="card" style={{overflow:'hidden'}}>
        <table className="tbl">
          <thead><tr>
            <th>SKU</th><th>Produkt</th>
            <th style={{textAlign:'right'}}>Bežná cena</th>
            <th style={{textAlign:'right'}}>Individuálna cena</th>
            <th style={{textAlign:'right'}}>Zľava</th>
            <th></th>
          </tr></thead>
          <tbody>
            {(data.prices || []).length === 0 && (
              <tr><td colSpan={6} style={{textAlign:'center', padding:30, color:'var(--ink-500)'}}>Žiadne individuálne ceny. Pridajte produkt vyššie.</td></tr>
            )}
            {(data.prices || []).map(p => {
              const isDeleted = toDelete.includes(p.product_id);
              const currentValue = dirty[p.product_id] !== undefined ? dirty[p.product_id] : p.individual_price;
              const priceNum = parseFloat(String(currentValue).replace(',', '.'));
              const discount = (priceNum > 0 && p.regular_price > 0) ? Math.round((1 - priceNum / p.regular_price) * 100 * 10) / 10 : null;
              return (
                <tr key={p.product_id} style={{opacity: isDeleted ? 0.45 : 1, textDecoration: isDeleted ? 'line-through' : 'none'}}>
                  <td className="mono small">{p.product_sku || '—'}</td>
                  <td>{p.product_name}</td>
                  <td style={{textAlign:'right'}} className="small">{formatCurrency(p.regular_price)}</td>
                  <td style={{textAlign:'right'}}>
                    {isDeleted ? formatCurrency(p.individual_price) : (
                      <input
                        className="input mono"
                        value={currentValue}
                        onChange={e => setNew(p.product_id, e.target.value)}
                        inputMode="decimal"
                        style={{width:110, height:26, textAlign:'right'}}
                      />
                    )}
                  </td>
                  <td style={{textAlign:'right'}}>
                    {discount != null && <span className={`chip ${discount > 0 ? 'green' : 'red'}`}>{discount > 0 ? '-' : '+'}{Math.abs(discount)}%</span>}
                  </td>
                  <td style={{textAlign:'right'}}>
                    {isDeleted
                      ? <button className="btn btn-xs" onClick={() => undoDelete(p.product_id)}>Vrátiť</button>
                      : <button className="btn btn-xs btn-danger" onClick={() => markDelete(p.product_id)} title="Označiť na zmazanie"><Ico.x/></button>
                    }
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {totalChanges > 0 && (
        <div className="small muted" style={{textAlign:'center', marginTop:10}}>
          <b>{totalChanges}</b> {totalChanges === 1 ? 'neuložená zmena' : 'neuložených zmien'}. Kliknite na <b>Uložiť</b> hore.
        </div>
      )}
    </AppShell>
  );
}

function IndividualPricing() {
  const [editUserId, setEditUserId] = React.useState(null);
  const [tab, setTab] = React.useState('with');         // 'with' | 'add'
  // Tab "with" — real customers with at least one product_price_* meta
  const [withList, setWithList] = React.useState([]);
  const [withLoading, setWithLoading] = React.useState(true);
  const [withError, setWithError] = React.useState(null);
  // Tab "add" — search WooCommerce customers to start a new price list
  const [addSearch, setAddSearch] = React.useState('');
  const [addResults, setAddResults] = React.useState([]);
  const [addSearching, setAddSearching] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  async function reloadWith() {
    setWithLoading(true);
    const r = await API.listCustomersWithPrices();
    setWithLoading(false);
    if (r.status === 503) { setWithError('not_configured'); return; }
    if (r.status === 404 || r.body.error === 'bridge_not_installed') { setWithError('bridge_missing'); return; }
    if (!r.ok) { setWithError(r.body.message || 'Chyba.'); return; }
    setWithError(null);
    setWithList(r.body.customers || []);
  }
  React.useEffect(() => { reloadWith(); }, []);

  // Debounced search for tab "add"
  React.useEffect(() => {
    if (tab !== 'add') return;
    if (!addSearch || addSearch.length < 2) { setAddResults([]); return; }
    const id = setTimeout(async () => {
      setAddSearching(true);
      const r = await API.listCustomers({ per_page: 20, search: addSearch });
      setAddSearching(false);
      if (r.ok) setAddResults(r.body.customers || []);
    }, 300);
    return () => clearTimeout(id);
  }, [addSearch, tab]);

  if (editUserId != null) {
    return (
      <>
        {toast && <Toast kind={toast.kind} onClose={() => setToast(null)}>{toast.text}</Toast>}
        <IndividualPricingEditor
          userId={editUserId}
          onBack={() => { setEditUserId(null); reloadWith(); }}
          notify={(kind, text) => setToast({ kind, text })}
        />
      </>
    );
  }

  if (withError === 'not_configured') {
    return (
      <AppShell active="pricing" crumbs={['CRM','Individuálne ceny']}>
        <div className="page-head"><div><h1>Individuálne ceny</h1></div></div>
        <NotConnected integration="WordPress"/>
      </AppShell>
    );
  }
  if (withError === 'bridge_missing') {
    return (
      <AppShell active="pricing" crumbs={['CRM','Individuálne ceny']}>
        <div className="page-head"><div><h1>Individuálne cenníky</h1></div></div>
        <div className="card" style={{padding:24, textAlign:'center', maxWidth:560, margin:'30px auto'}}>
          <div style={{fontSize:42}}>🧩</div>
          <h3>WP bridge plugin je starý</h3>
          <p className="muted">Endpoint <code>/dd/v1/customers/with-prices</code> chýba. Re-uploadnite aktuálny <code>wp-plugin/dd-crm-bridge.php</code> do <code>mu-plugins/</code>.</p>
        </div>
      </AppShell>
    );
  }

  return (
    <AppShell active="pricing" crumbs={['CRM','Individuálne ceny']}>
      {toast && <Toast kind={toast.kind} onClose={() => setToast(null)}>{toast.text}</Toast>}

      <div className="page-head">
        <div>
          <h1>Individuálne cenníky</h1>
          <p>Vyberte zákazníka a upravte jeho individuálne ceny (<code>product_price_&lt;id&gt;</code> user meta).</p>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={reloadWith}><Ico.upload/>Obnoviť</button>
        </div>
      </div>

      <div className="tabs">
        <button className={tab === 'with' ? 'active' : ''} onClick={() => setTab('with')}>
          S cenníkom <span className="muted">{withLoading ? '…' : withList.length}</span>
        </button>
        <button className={tab === 'add' ? 'active' : ''} onClick={() => setTab('add')}>
          + Pridať cenník novému zákazníkovi
        </button>
      </div>

      {tab === 'with' ? (
        <div className="card" style={{overflow:'hidden'}}>
          {withLoading ? <div style={{padding:20}} className="muted">Načítavam…</div> : withList.length === 0 ? (
            <div style={{padding:30, textAlign:'center', color:'var(--ink-500)'}}>
              Žiadni zákazníci zatiaľ nemajú individuálne ceny. Prepnite sa na záložku <b>Pridať cenník novému zákazníkovi</b>.
            </div>
          ) : (
            <table className="tbl">
              <thead><tr>
                <th>Zákazník</th><th>Firma</th><th>IČO</th><th style={{textAlign:'right'}}>Počet cien</th><th></th>
              </tr></thead>
              <tbody>
                {withList.map(c => (
                  <tr key={c.id}>
                    <td>
                      <div style={{fontWeight:500}}>{c.name || c.login}</div>
                      <div className="small muted">{c.email}</div>
                    </td>
                    <td>{c.company_name || '—'} {c.is_company && <span className="chip navy" style={{marginLeft:6, padding:'0 6px', fontSize:10}}>B2B</span>}</td>
                    <td className="mono small">{c.company_id || '—'}</td>
                    <td style={{textAlign:'right'}}><span className="chip green">{c.price_count}</span></td>
                    <td style={{textAlign:'right'}}>
                      <button className="btn btn-xs btn-primary" onClick={() => setEditUserId(c.id)}>Upraviť ceny</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      ) : (
        <div>
          <div className="filters">
            <div style={{position:'relative', flex:1, maxWidth:400}}>
              <Ico.search style={{position:'absolute', left:10, top:9, color:'var(--ink-400)'}}/>
              <input
                className="input"
                placeholder="Hľadať WooCommerce zákazníka — meno, e-mail, firma…"
                style={{paddingLeft:30, width:'100%'}}
                value={addSearch}
                onChange={e => setAddSearch(e.target.value)}
                autoFocus
              />
            </div>
            {addSearching && <div className="small muted">Hľadám…</div>}
          </div>

          <div className="card" style={{overflow:'hidden'}}>
            {addSearch.length < 2 ? (
              <div style={{padding:30, textAlign:'center', color:'var(--ink-500)'}}>
                Zadajte aspoň 2 znaky pre vyhľadanie zákazníka z WooCommerce.
              </div>
            ) : addResults.length === 0 ? (
              <div style={{padding:20}} className="muted">Žiadne výsledky.</div>
            ) : (
              <table className="tbl">
                <thead><tr>
                  <th>Zákazník</th><th>Firma</th><th>IČO</th><th>Segment</th><th></th>
                </tr></thead>
                <tbody>
                  {addResults.map(c => (
                    <tr key={c.id}>
                      <td>
                        <div style={{fontWeight:500}}>{(c.first_name + ' ' + c.last_name).trim() || c.username || '—'}</div>
                        <div className="small muted">{c.email}</div>
                      </td>
                      <td>{c.company_name || c.billing_company || '—'}</td>
                      <td className="mono small">{c.company_id || '—'}</td>
                      <td>{c.is_company ? <span className="chip navy">B2B</span> : <span className="chip gray">B2C</span>}</td>
                      <td style={{textAlign:'right'}}>
                        <button className="btn btn-xs btn-primary" onClick={() => setEditUserId(c.id)}>Pridať cenník</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
      )}
    </AppShell>
  );
}

function AiChatAnswer() {
  return (
    <div className="app">
      <AiSidebar/>
      <div className="main">
        <div className="topbar">
          <div className="crumbs"><span>AI Asistent</span><span className="sep">/</span><b>Cenová analýza Huawei</b></div>
          <div className="hstack" style={{marginLeft:14}}>
            <div className="seg"><button>Auto</button><button className="active">Sonet 4.5</button><button>Opus</button></div>
            <span className="chip green dot">WooCommerce</span>
            <span className="chip navy dot">SuperFaktúra</span>
          </div>
          <div style={{marginLeft:'auto'}}><button className="btn btn-sm">Zdieľať</button></div>
        </div>
        <div className="content" style={{padding:0, display:'flex', flexDirection:'column'}}>
          <div style={{flex:1, overflow:'auto', padding:'20px 0'}}>
            <div style={{maxWidth:820, margin:'0 auto', display:'flex', flexDirection:'column', gap:18}}>
              {/* user */}
              <div style={{alignSelf:'flex-end', maxWidth:'70%'}}>
                <div style={{background:'var(--navy-800)', color:'#fff', padding:'10px 14px', borderRadius:'14px 14px 4px 14px', fontSize:13.5}}>
                  Porovnaj predaj Huawei SUN2000 meničov s GoodWe za posledný kvartál. Ukáž marže.
                </div>
                <div className="small muted" style={{textAlign:'right', marginTop:4}}>9:42</div>
              </div>
              {/* assistant */}
              <div style={{display:'flex', gap:10, maxWidth:'85%'}}>
                <div style={{width:32, height:32, borderRadius:8, background:'linear-gradient(135deg, var(--navy-800), var(--navy-500))', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, color:'#fff'}}><Ico.sparkles/></div>
                <div style={{flex:1}}>
                  <div style={{background:'#fff', border:'1px solid var(--border)', padding:'12px 14px', borderRadius:'14px 14px 14px 4px', fontSize:13.5, lineHeight:1.55}}>
                    <div style={{fontWeight:600, marginBottom:6}}>Q1 2026 · porovnanie predaja meničov</div>
                    <p style={{margin:'0 0 10px'}}>Čerpám dáta z WooCommerce (objednávky) a SuperFaktúra (vystavené faktúry). Tu je sumár:</p>
                    <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:10}}>
                      <div style={{border:'1px solid var(--border)', borderRadius:8, padding:10}}>
                        <div className="small muted">Huawei SUN2000</div>
                        <div style={{fontSize:18, fontWeight:700}}>142 ks · 186 400 €</div>
                        <div className="small" style={{color:'var(--green-500)'}}>Marža 22,4 %</div>
                      </div>
                      <div style={{border:'1px solid var(--border)', borderRadius:8, padding:10}}>
                        <div className="small muted">GoodWe GW/ET</div>
                        <div style={{fontSize:18, fontWeight:700}}>98 ks · 118 700 €</div>
                        <div className="small" style={{color:'var(--amber-500)'}}>Marža 17,1 %</div>
                      </div>
                    </div>
                    <p style={{margin:'0 0 6px'}}><b>Zistenie:</b> Huawei predáva o 45% viac kusov a má o 5,3 p.b. vyššiu maržu. GoodWe však dominuje v segmente domácnosti do 10kW.</p>
                    <div className="hstack" style={{marginTop:10}}>
                      <button className="btn btn-xs">Otvoriť v reportoch</button>
                      <button className="btn btn-xs"><Ico.download/>Export CSV</button>
                      <button className="btn btn-xs">Vytvoriť úlohu v ClickUp</button>
                    </div>
                  </div>
                  <div className="small muted" style={{marginTop:4, display:'flex', gap:8}}>
                    <span>9:43</span><span>·</span>
                    <span>Zdroje: <b>WooCommerce</b>, <b>SuperFaktúra</b></span>
                    <span>·</span>
                    <a style={{color:'var(--navy-700)', cursor:'pointer'}}>Skopírovať</a>
                    <a style={{color:'var(--navy-700)', cursor:'pointer'}}>Regenerovať</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div style={{padding:'12px 20px 18px', borderTop:'1px solid var(--border)', background:'var(--bg)'}}>
            <div style={{maxWidth:820, margin:'0 auto', background:'#fff', border:'1px solid var(--border-strong)', borderRadius:12, padding:10}}>
              <textarea placeholder="Pýtajte sa ďalej…" style={{width:'100%', border:'none', outline:'none', resize:'none', fontFamily:'var(--font)', fontSize:13.5, minHeight:38}} defaultValue=""/>
              <div className="hstack" style={{marginTop:4}}>
                <button className="btn btn-ghost btn-xs"><Ico.upload/>Príloha</button>
                <button className="btn btn-ghost btn-xs"><Ico.sparkles/>Skill</button>
                <div style={{marginLeft:'auto'}}><button className="btn btn-primary btn-sm">Odoslať</button></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Integrations() {
  const ints = [
    { n:'WooCommerce', d:'Objednávky, produkty, zákazníci', on:true, stat:'Posledná sync pred 2 min', c:'#7f54b3' },
    { n:'SuperFaktúra', d:'Vystavovanie faktúr, úhrady, upomienky', on:true, stat:'Prepojené · 284 faktúr', c:'#2a9d5f' },
    { n:'GoodWe SEMS', d:'Monitoring FV inštalácií, výkony, chyby', on:true, stat:'12 aktívnych inštalácií', c:'#f3a712' },
    { n:'ClickUp', d:'Projektové úlohy, servisné výjazdy', on:true, stat:'Workspace: D&D Energy', c:'#7b68ee' },
    { n:'Packeta / Zásielkovňa', d:'Doprava, tracking, štítky', on:true, stat:'Sync OK', c:'#b02838' },
    { n:'FinStat', d:'Automatické overovanie IČO / DIČ', on:true, stat:'API kľúč aktívny', c:'#133258' },
    { n:'Solax Cloud', d:'Monitoring Solax meničov', on:false, stat:'Dostupné · pripojiť', c:'#00a859' },
    { n:'Mailchimp', d:'E-mail kampane a newslettery', on:false, stat:'Dostupné · pripojiť', c:'#ffe01b' },
    { n:'Google Calendar', d:'Kalendár výjazdov a schôdzok', on:false, stat:'Dostupné · pripojiť', c:'#4285F4' },
  ];
  return (
    <AppShell active="settings" crumbs={['Nastavenia','Integrácie']}>
      <div className="page-head">
        <div><h1>Integrácie</h1><p>6 aktívnych z 9 dostupných · API kľúče, webhooky, synchronizácia</p></div>
        <div className="page-head-actions"><button className="btn btn-primary"><Ico.plus/>Pridať integráciu</button></div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:12}}>
        {ints.map((x,i) => (
          <div key={i} className={`mod-tile ${x.on?'':'off'}`}>
            <div className="hstack">
              <div style={{width:36, height:36, borderRadius:8, background:x.c, color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:13}}>{x.n.slice(0,2).toUpperCase()}</div>
              <div style={{flex:1, minWidth:0}}><h4>{x.n}</h4><div className="small muted">{x.stat}</div></div>
              <div className={`toggle ${x.on?'on':''}`}/>
            </div>
            <p>{x.d}</p>
            <div className="mod-foot">
              <span className="mod-users">{x.on ? 'Spracované cez API v2' : 'Nepripojené'}</span>
              <button className="btn btn-xs">{x.on?'Konfigurovať':'Pripojiť'}</button>
            </div>
          </div>
        ))}
      </div>
    </AppShell>
  );
}

function AppLauncher() {
  const apps = [
    { n:'Hlavný eshop', u:'ddenergy.sk', c:'linear-gradient(135deg, #0e2744, #23507f)', ext:true },
    { n:'CRM · Prehľad', u:'crm.ddenergy.sk/#/dashboard', c:'linear-gradient(135deg, #f3a712, #c47a00)', active:true },
    { n:'CRM · Objednávky', u:'crm.ddenergy.sk/#/objednavky', c:'linear-gradient(135deg, #133258, #3a6da0)' },
    { n:'CRM · Produkty', u:'crm.ddenergy.sk/#/produkty', c:'linear-gradient(135deg, #1a3f6b, #6a91bb)' },
    { n:'CRM · AI asistent', u:'crm.ddenergy.sk/#/ai', c:'linear-gradient(135deg, #3a6da0, #6a91bb)' },
    { n:'CRM · Kalendár & dovolenky', u:'crm.ddenergy.sk/#/kalendar', c:'linear-gradient(135deg, #2a9d5f, #135e37)' },
    { n:'CRM · Servis (GoodWe)', u:'crm.ddenergy.sk/#/servis', c:'linear-gradient(135deg, #d64545, #7c1d1d)' },
    { n:'CRM · Datasheety', u:'crm.ddenergy.sk/#/datasheety', c:'linear-gradient(135deg, #5b6b82, #2a3a52)' },
    { n:'CRM · Realizácie', u:'crm.ddenergy.sk/#/realizacie', c:'linear-gradient(135deg, #7b68ee, #5b47c9)' },
  ];
  return (
    <AppShell active="dashboard" crumbs={['Spustenie modulov']}>
      <div className="page-head">
        <div><h1>Moduly CRM</h1><p>Všetky manažérske nástroje beli na jednej doméne <b>crm.ddenergy.sk</b> · prepínanie cez hash routing <span className="mono">/#/modul</span></p></div>
      </div>
      <div style={{display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14}}>
        {apps.map(a => (
          <div key={a.n} className="card" style={{padding:0, overflow:'hidden', cursor:'pointer', position:'relative'}}>
            <div style={{height:80, background:a.c, position:'relative'}}>
              {a.active && <span className="chip amber dot" style={{position:'absolute', top:10, right:10}}>Ste tu</span>}
              {a.ext && <span className="chip" style={{position:'absolute', top:10, right:10, background:'rgba(255,255,255,0.92)'}}>Externý</span>}
            </div>
            <div style={{padding:'12px 14px'}}>
              <div style={{fontWeight:600, fontSize:14}}>{a.n}</div>
              <div className="small mono muted">{a.u}</div>
              <div className="divider" style={{margin:'10px 0 8px'}}/>
              <div className="hstack">
                <span className="small" style={{color:'var(--green-500)', fontWeight:500}}>● Dostupné</span>
                <button className="btn btn-xs" style={{marginLeft:'auto'}}>{a.ext?'Otvoriť ↗':'Prejsť →'}</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </AppShell>
  );
}

Object.assign(window, { B2BApprovals, IndividualPricing, AiChatAnswer, Integrations, AppLauncher });
