// Forms — WPForms inbox in ERP.
// Layout: left rail = list of forms (with unread badges), right = entries table
// of the selected form. Click row → detail modal with all fields, mark/star/trash.
//
// Backend status:
//   - WPForms Pro → reads wp_wpforms_entries via dd-erp-bridge
//   - WPForms Lite or no plugin → /diag returns pro:false → we show explainer

function FormsScreen() {
  const [diag, setDiag]           = React.useState(null);    // null | {wpforms, forms_count, entries_count, note}
  const [forms, setForms]         = React.useState([]);
  const [activeFormId, setActiveFormId] = React.useState(null);  // null = all forms
  const [statusFilter, setStatusFilter] = React.useState('');    // '', 'unread', 'starred', 'trash'
  const [search, setSearch]       = React.useState('');
  const [entries, setEntries]     = React.useState({ items: [], total: 0, page: 1, pages: 1, loading: true });
  const [page, setPage]           = React.useState(1);
  const [openEntry, setOpenEntry] = React.useState(null);    // entry id being shown in detail
  const [toast, setToast]         = React.useState(null);
  const [error, setError]         = React.useState(null);

  const canEdit = window.hasPerm ? window.hasPerm('forms.edit') : false;

  // ── Initial load: diag + forms list ──
  React.useEffect(() => {
    (async () => {
      const d = await API.formsDiag();
      if (d.status === 503) { setError('wordpress_not_configured'); return; }
      if (d.status === 403) { setError('forbidden'); return; }
      if (d.ok && d.body.ok) setDiag(d.body);
      const fl = await API.formsList();
      if (fl.ok && fl.body.ok) setForms(fl.body.forms || []);
    })();
  }, []);

  // ── Entries reload on filter change ──
  React.useEffect(() => { loadEntries(); /* eslint-disable-next-line */ }, [activeFormId, statusFilter, page]);
  React.useEffect(() => {
    const id = setTimeout(() => { setPage(1); loadEntries(); }, 350);
    return () => clearTimeout(id);
    // eslint-disable-next-line
  }, [search]);

  async function loadEntries() {
    if (!diag || !diag.wpforms?.pro) { setEntries({ items: [], total: 0, page: 1, pages: 1, loading: false }); return; }
    setEntries(e => ({ ...e, loading: true }));
    const params = { page, per_page: 25 };
    if (activeFormId) params.form_id = activeFormId;
    if (statusFilter) params.status  = statusFilter;
    if (search)       params.search  = search;
    const r = await API.formsEntries(params);
    if (!r.ok || !r.body.ok) {
      setEntries({ items: [], total: 0, page: 1, pages: 1, loading: false });
      if (r.status !== 404) setToast({ kind: 'error', text: r.body?.message || 'Nepodarilo sa načítať záznamy.' });
      return;
    }
    setEntries({
      items: r.body.entries || [], total: r.body.total || 0,
      page:  r.body.page  || 1, pages: r.body.pages || 1, loading: false,
    });
  }

  async function reloadForms() {
    const fl = await API.formsList();
    if (fl.ok && fl.body.ok) setForms(fl.body.forms || []);
  }

  async function patchEntry(id, patch) {
    const r = await API.formsEntryUpdate(id, patch);
    if (!r.ok || !r.body.ok) {
      setToast({ kind: 'error', text: r.body?.message || 'Zmena zlyhala.' });
      return false;
    }
    return true;
  }

  async function deleteEntry(id, force) {
    const r = await API.formsEntryDelete(id, force);
    if (!r.ok || !r.body.ok) {
      setToast({ kind: 'error', text: r.body?.message || 'Mazanie zlyhalo.' });
      return false;
    }
    setToast({ kind: 'success', text: force ? 'Záznam trvalo zmazaný.' : 'Záznam v koši.' });
    setOpenEntry(null);
    loadEntries();
    reloadForms();
    return true;
  }

  // ─── Empty / error states ───
  if (error === 'wordpress_not_configured') {
    return (
      <AppShell active="forms" crumbs={['ERP','Formuláre']}>
        <div className="page-head"><div><h1>Formuláre</h1></div></div>
        <NotConnected integration="WordPress" slug="wordpress" message="Pre načítanie WPForms je potrebné nastaviť WordPress integráciu."/>
      </AppShell>
    );
  }

  return (
    <AppShell active="forms" crumbs={['ERP','Formuláre']}>
      {toast && <Toast kind={toast.kind} onClose={() => setToast(null)}>{toast.text}</Toast>}

      <div className="page-head">
        <div>
          <h1>Formuláre <span className="muted" style={{fontWeight:400, fontSize:14}}>· WPForms</span></h1>
          <p>
            {diag
              ? (diag.wpforms?.active
                  ? `${diag.forms_count} formulárov · ${diag.entries_count} záznamov ${diag.wpforms.pro ? '· WPForms Pro' : '· WPForms Lite (limity)'}`
                  : 'WPForms nie je nainštalovaný na stránke.')
              : 'Načítavam…'}
          </p>
        </div>
        <div className="page-head-actions">
          <button className="btn" onClick={() => { reloadForms(); loadEntries(); }}><Ico.refresh/>Obnoviť</button>
        </div>
      </div>

      {/* Pro/Lite warning bar */}
      {diag && diag.wpforms?.active && !diag.wpforms.pro && (
        <div style={{
          padding:'10px 14px', background:'var(--amber-50, #fffbeb)',
          border:'1px solid var(--amber-200, #fde68a)', borderRadius:8, marginBottom:12, fontSize:13,
        }}>
          ⚠️ <b>WPForms Lite</b> verzia neukladá záznamy do databázy — vidíte len zoznam formulárov, nie odoslané dáta.
          Pre plnú funkcionalitu prejdite na WPForms Pro alebo doplňte vlastný logger (TODO v bridge plugine).
          {diag.note && <div className="muted" style={{marginTop:4}}>{diag.note}</div>}
        </div>
      )}

      <div style={{display:'grid', gridTemplateColumns:'280px 1fr', gap:14, alignItems:'start'}}>
        {/* ── Left rail: forms list ── */}
        <div className="card" style={{padding:0, overflow:'hidden', position:'sticky', top:14}}>
          <div style={{padding:'10px 12px', borderBottom:'1px solid var(--border)', fontWeight:600, fontSize:13}}>
            Formuláre
          </div>
          <div style={{maxHeight:'70vh', overflow:'auto'}}>
            <FormRailItem
              active={activeFormId === null}
              onClick={() => { setActiveFormId(null); setPage(1); }}
              title="Všetky formuláre"
              sub={`${diag?.entries_count || 0} záznamov spolu`}
              unread={forms.reduce((s, f) => s + (f.entries_unviewed || 0), 0)}
            />
            {forms.length === 0 && (
              <div style={{padding:20, textAlign:'center', color:'var(--ink-500)', fontSize:12.5}}>
                Žiadne formuláre.
              </div>
            )}
            {forms.map(f => (
              <FormRailItem
                key={f.id}
                active={activeFormId === f.id}
                onClick={() => { setActiveFormId(f.id); setPage(1); }}
                title={f.title}
                sub={`${f.fields_count} polí · ${f.entries_total} záznamov`}
                unread={f.entries_unviewed}
              />
            ))}
          </div>
        </div>

        {/* ── Right: entries table ── */}
        <div className="card" style={{overflow:'hidden'}}>
          <div style={{display:'flex', gap:8, padding:'10px 12px', borderBottom:'1px solid var(--border)', alignItems:'center'}}>
            <select className="select" value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(1); }} style={{maxWidth:160}}>
              <option value="">Všetky</option>
              <option value="unread">Neprečítané</option>
              <option value="read">Prečítané</option>
              <option value="starred">Označené ⭐</option>
              <option value="trash">Kôš</option>
            </select>
            <input
              className="input"
              placeholder="🔍 Hľadať v poliach…"
              value={search}
              onChange={e => setSearch(e.target.value)}
              style={{flex:1}}
            />
          </div>

          {entries.loading ? (
            <div style={{padding:20, color:'var(--ink-500)'}}>Načítavam záznamy…</div>
          ) : entries.items.length === 0 ? (
            <div style={{padding:40, textAlign:'center', color:'var(--ink-500)'}}>
              {diag?.wpforms?.pro
                ? 'Žiadne záznamy pre tento filter.'
                : 'WPForms Pro nie je aktívne — záznamy sa nevedia načítať.'}
            </div>
          ) : (
            <div style={{overflow:'auto'}}>
              <table className="tbl">
                <thead><tr>
                  <th style={{width:30}}></th>
                  <th>Formulár</th>
                  <th>Náhľad (prvé polia)</th>
                  <th style={{width:140}}>Dátum</th>
                  <th style={{width:90, textAlign:'right'}}></th>
                </tr></thead>
                <tbody>
                  {entries.items.map(e => (
                    <tr key={e.id}
                      style={{ background: e.viewed ? '' : 'var(--navy-50, #eff6ff)', cursor:'pointer' }}
                      onClick={() => setOpenEntry(e.id)}
                    >
                      <td>{e.starred ? <span title="Označené">⭐</span> : (e.viewed ? '' : <span title="Neprečítané" style={{color:'var(--navy-700)'}}>●</span>)}</td>
                      <td className="small">{e.form_title}</td>
                      <td className="small" style={{color:'var(--ink-700)'}}>
                        <PreviewValues values={e.values}/>
                      </td>
                      <td className="small muted">{formatLocalDate(e.date)}</td>
                      <td style={{textAlign:'right'}}>
                        <button className="btn btn-xs" onClick={(ev) => { ev.stopPropagation(); setOpenEntry(e.id); }}>Otvoriť</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {entries.pages > 1 && (
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 14px', borderTop:'1px solid var(--border)', fontSize:12}}>
              <span className="muted">Strana {entries.page} z {entries.pages} · {entries.total} záznamov</span>
              <div className="hstack">
                <button className="btn btn-xs" disabled={page <= 1} onClick={() => setPage(p => Math.max(1, p - 1))}>← Prev</button>
                <button className="btn btn-xs" disabled={page >= entries.pages} onClick={() => setPage(p => Math.min(entries.pages, p + 1))}>Next →</button>
              </div>
            </div>
          )}
        </div>
      </div>

      {openEntry && (
        <FormEntryModal
          entryId={openEntry}
          canEdit={canEdit}
          onClose={() => setOpenEntry(null)}
          onChanged={() => { loadEntries(); reloadForms(); }}
          onPatch={patchEntry}
          onDelete={deleteEntry}
          notify={(kind, text) => setToast({ kind, text })}
        />
      )}
    </AppShell>
  );
}

// ─── Left-rail row ────────────────────────────────────────────────────────
function FormRailItem({ active, onClick, title, sub, unread }) {
  return (
    <div
      onClick={onClick}
      style={{
        padding:'10px 12px', borderBottom:'1px solid var(--border)',
        cursor:'pointer',
        background: active ? 'var(--navy-50, #eff6ff)' : '#fff',
        borderLeft: active ? '3px solid var(--navy-800)' : '3px solid transparent',
      }}
    >
      <div style={{display:'flex', alignItems:'center', gap:6}}>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:13, fontWeight: active ? 600 : 500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{title}</div>
          <div className="small muted">{sub}</div>
        </div>
        {unread > 0 && (
          <span style={{
            background:'var(--red-500, #dc2626)', color:'#fff', borderRadius:10,
            padding:'1px 7px', fontSize:11, fontWeight:700, minWidth:18, textAlign:'center',
          }}>{unread}</span>
        )}
      </div>
    </div>
  );
}

// ─── Inline preview of first 2 field values ───────────────────────────────
function PreviewValues({ values }) {
  if (!values || values.length === 0) return <span className="muted">(prázdne)</span>;
  const shown = values.filter(v => v.value && String(v.value).trim()).slice(0, 2);
  if (shown.length === 0) return <span className="muted">(prázdne)</span>;
  return (
    <>
      {shown.map((v, i) => (
        <span key={i} style={{marginRight:14}}>
          <span className="muted" style={{marginRight:4}}>{v.label || `Pole #${v.field_id}`}:</span>
          {String(v.value).slice(0, 60)}{String(v.value).length > 60 ? '…' : ''}
        </span>
      ))}
    </>
  );
}

function formatLocalDate(s) {
  if (!s) return '';
  try {
    return new Intl.DateTimeFormat('sk-SK', { day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' })
      .format(new Date(String(s).replace(' ', 'T') + (s.endsWith('Z') ? '' : 'Z')));
  } catch { return String(s); }
}

// ─── Entry detail modal ───────────────────────────────────────────────────
function FormEntryModal({ entryId, canEdit, onClose, onChanged, onPatch, onDelete, notify }) {
  const [entry, setEntry]   = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [busy, setBusy]     = React.useState(null);  // 'star' | 'trash' | 'reply' | etc.
  const [reply, setReply]   = React.useState(false); // open composer

  React.useEffect(() => {
    let alive = true;
    (async () => {
      setLoading(true);
      const r = await API.formsEntryDetail(entryId);
      if (!alive) return;
      setLoading(false);
      if (!r.ok || !r.body.ok) {
        notify('error', r.body?.message || 'Nepodarilo sa načítať detail.');
        onClose();
        return;
      }
      setEntry(r.body.entry);
      onChanged?.();   // detail auto-marks viewed on backend → refresh counts
    })();
    return () => { alive = false; };
    // eslint-disable-next-line
  }, [entryId]);

  async function toggleStar() {
    if (!entry) return;
    setBusy('star');
    const ok = await onPatch(entry.id, { starred: !entry.starred });
    setBusy(null);
    if (ok) { setEntry({ ...entry, starred: !entry.starred }); onChanged?.(); }
  }
  async function markUnread() {
    if (!entry) return;
    setBusy('unread');
    const ok = await onPatch(entry.id, { viewed: false });
    setBusy(null);
    if (ok) { setEntry({ ...entry, viewed: false }); onChanged?.(); onClose(); }
  }
  async function trash() {
    setBusy('trash');
    await onDelete(entry.id, false);
    setBusy(null);
  }

  // Try to auto-detect an email field for "Reply via mail" link
  const emailField = entry?.values?.find(v => /email/i.test(v.type) || /email|e[-_ ]?mail|mail/i.test(v.label || ''))?.value;
  const phoneField = entry?.values?.find(v => /phone|tel|telef/i.test(v.type) || /tel|phone|telef/i.test(v.label || ''))?.value;
  const nameField  = entry?.values?.find(v => /name/i.test(v.type) || /meno|name/i.test(v.label || ''))?.value;

  // Compact icon-only button for footer toolbar (saves space, keeps semantics via title)
  const IconBtn = ({ title, onClick, disabled, tone = 'default', children, href }) => {
    const palette = {
      default: { color: 'var(--ink-700)', hover: 'var(--bg)' },
      danger:  { color: 'var(--red-500, #dc2626)', hover: 'var(--red-100, #fee2e2)' },
      gold:    { color: '#d97706', hover: '#fef3c7' },
    }[tone];
    const style = {
      display:'inline-flex', alignItems:'center', justifyContent:'center',
      width:32, height:32, borderRadius:6, border:'1px solid var(--border)',
      background:'#fff', color: palette.color, cursor: disabled ? 'not-allowed' : 'pointer',
      opacity: disabled ? 0.5 : 1, fontSize:14, padding:0,
    };
    if (href) return <a href={href} title={title} style={style} target="_blank" rel="noopener noreferrer">{children}</a>;
    return <button type="button" title={title} onClick={onClick} disabled={disabled} style={style}>{children}</button>;
  };

  // Build initials for the contact avatar (fallback to ?)
  const initials = (nameField || emailField || '?').split(/[\s@.]/).filter(Boolean).slice(0, 2).map(p => p[0]).join('').toUpperCase();

  return (
    <Modal
      title={entry ? `${entry.form_title} · záznam #${entry.id}` : 'Záznam…'}
      width={720}
      onClose={onClose}
      footer={(
        <div style={{display:'flex', gap:8, alignItems:'center', width:'100%', flexWrap:'wrap'}}>
          {emailField && canEdit && (
            <button
              className="btn btn-primary"
              onClick={() => setReply(true)}
              title="Otvorí editor odpovede s automaticky vloženým pôvodným formulárom v tele e-mailu"
              style={{height:36, padding:'0 16px', fontSize:13, fontWeight:600}}
            >
              ✉ Odpovedať na e-mail
            </button>
          )}

          {/* Compact icon toolbar — quick actions, no wrapping text */}
          <div style={{display:'flex', gap:4, marginLeft:emailField && canEdit ? 4 : 0}}>
            {phoneField && (
              <IconBtn title={`Zavolať na ${phoneField}`} href={`tel:${String(phoneField).replace(/\s+/g, '')}`}>📞</IconBtn>
            )}
            {emailField && (
              <IconBtn title="Otvoriť v poštovej apke (mailto)" href={`mailto:${emailField}`}>📧</IconBtn>
            )}
            {canEdit && entry && (
              <IconBtn
                title={entry.starred ? 'Zrušiť hviezdu' : 'Označiť hviezdou'}
                onClick={toggleStar} disabled={!!busy}
                tone={entry.starred ? 'gold' : 'default'}
              >{entry.starred ? '★' : '☆'}</IconBtn>
            )}
            {canEdit && entry && (
              <IconBtn title="Označiť ako neprečítané" onClick={markUnread} disabled={!!busy}>●</IconBtn>
            )}
          </div>

          <div style={{flex:1}}/>

          {canEdit && entry && (
            <button
              className="btn"
              onClick={trash}
              disabled={!!busy}
              title="Presunúť do koša vo WordPress"
              style={{color:'var(--red-500, #dc2626)', height:36}}
            >
              {busy === 'trash' ? 'Mažem…' : <>🗑 Do koša</>}
            </button>
          )}
          <button className="btn" onClick={onClose} style={{height:36}}>Zavrieť</button>
        </div>
      )}
    >
      {loading && <div className="muted">Načítavam…</div>}
      {entry && !loading && (
        <>
          {/* Meta strip — date, IP, status chip */}
          <div style={{
            display:'flex', alignItems:'center', gap:10, flexWrap:'wrap',
            paddingBottom:14, marginBottom:14, borderBottom:'1px solid var(--border)',
            fontSize:12.5, color:'var(--ink-500)',
          }}>
            <span>📅 {formatLocalDate(entry.date)}</span>
            {entry.user_ip && (
              <>
                <span style={{color:'var(--ink-300)'}}>·</span>
                <span>IP <span className="mono">{entry.user_ip}</span></span>
              </>
            )}
            {entry.starred && (
              <>
                <span style={{color:'var(--ink-300)'}}>·</span>
                <span style={{color:'#d97706'}}>★ Označené</span>
              </>
            )}
            <div style={{flex:1}}/>
            <span style={{
              padding:'2px 10px', borderRadius:10, fontSize:11, fontWeight:600,
              background: entry.viewed ? 'var(--ink-100, #e5e7eb)' : 'var(--navy-50, #eff6ff)',
              color:      entry.viewed ? 'var(--ink-600, #6b7280)' : 'var(--navy-700, #1d4ed8)',
            }}>{entry.viewed ? '✓ Prečítané' : '● Neprečítané'}</span>
          </div>

          {/* Contact summary — bigger, prominent, primary identity card */}
          {(nameField || emailField || phoneField) && (
            <div style={{
              display:'flex', gap:14, alignItems:'center',
              padding:'14px 16px', marginBottom:18, borderRadius:10,
              background:'linear-gradient(135deg, var(--navy-50, #eff6ff), #ffffff)',
              border:'1px solid var(--navy-200, #bfdbfe)',
            }}>
              <div style={{
                width:48, height:48, flex:'0 0 48px', borderRadius:'50%',
                background:'var(--navy-800, #0e2744)', color:'#fff',
                display:'grid', placeItems:'center',
                fontSize:18, fontWeight:600, letterSpacing:0.5,
              }}>{initials}</div>
              <div style={{flex:1, minWidth:0}}>
                {nameField && (
                  <div style={{fontSize:16, fontWeight:600, color:'var(--ink-900)', marginBottom:2}}>{nameField}</div>
                )}
                <div style={{display:'flex', gap:14, flexWrap:'wrap', fontSize:13}}>
                  {emailField && (
                    <a href={`mailto:${emailField}`} style={{color:'var(--navy-700)', textDecoration:'none', display:'inline-flex', alignItems:'center', gap:5}}>
                      📧 {emailField}
                    </a>
                  )}
                  {phoneField && (
                    <a href={`tel:${String(phoneField).replace(/\s+/g,'')}`} style={{color:'var(--navy-700)', textDecoration:'none', display:'inline-flex', alignItems:'center', gap:5}}>
                      📞 {phoneField}
                    </a>
                  )}
                </div>
              </div>
            </div>
          )}

          {/* Field list — clean table-like rows with bottom-border separation */}
          <div style={{fontSize:11, fontWeight:600, letterSpacing:0.6, textTransform:'uppercase', color:'var(--ink-500)', marginBottom:6}}>
            Odoslané údaje
          </div>
          <div style={{border:'1px solid var(--border)', borderRadius:8, overflow:'hidden', background:'#fff'}}>
            {(entry.values || []).map((v, i, arr) => (
              <div key={i} style={{
                display:'grid', gridTemplateColumns:'200px 1fr', gap:14, alignItems:'baseline',
                padding:'12px 16px',
                borderBottom: i < arr.length - 1 ? '1px solid var(--border)' : 'none',
                background: i % 2 === 0 ? '#fff' : 'var(--ink-50, #fafbfc)',
              }}>
                <div style={{fontSize:13, color:'var(--ink-600)', fontWeight:500}}>
                  {v.label || <span style={{fontStyle:'italic', color:'var(--ink-400)'}}>(bez popisu)</span>}
                </div>
                <div style={{fontSize:14, color:'var(--ink-900)', whiteSpace:'pre-wrap', wordBreak:'break-word'}}>
                  {v.value
                    ? (/email/i.test(v.type) ? <a href={`mailto:${v.value}`} style={{color:'var(--navy-700)'}}>{v.value}</a>
                      : /phone|tel/i.test(v.type) ? <a href={`tel:${String(v.value).replace(/\s+/g,'')}`} style={{color:'var(--navy-700)'}}>{v.value}</a>
                      : String(v.value))
                    : <span className="muted">—</span>}
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {reply && entry && (
        <ReplyComposerModal
          entry={entry}
          onClose={() => setReply(false)}
          onSent={() => { setReply(false); notify('success', 'E-mail odoslaný cez Microsoft 365.'); onClose(); onChanged?.(); }}
          notify={notify}
        />
      )}
    </Modal>
  );
}

// ─── Reply composer — sends via MS365 with quoted form auto-attached ─────
// The customer always sees a styled "Pôvodný formulár" block under the reply
// so they know exactly which submission this answer relates to.
function ReplyComposerModal({ entry, onClose, onSent, notify }) {
  const [draft, setDraft]   = React.useState(null);
  const [busy, setBusy]     = React.useState(false);
  const [error, setError]   = React.useState(null);
  const [to, setTo]         = React.useState('');
  const [subject, setSubject] = React.useState('');
  const [body, setBody]     = React.useState('');
  const [showPreview, setShowPreview] = React.useState(false);
  const bodyRef = React.useRef(null);

  React.useEffect(() => {
    (async () => {
      const r = await API.formsReplyDraft(entry.id);
      if (!r.ok || !r.body.ok) {
        setError(r.body?.message || 'Nepodarilo sa pripraviť koncept.');
        return;
      }
      setDraft(r.body);
      setTo(r.body.to || '');
      setSubject(r.body.subject || '');
      setBody(r.body.body_text || '');
      // Focus the body and place cursor at the [Sem napíšte ...] placeholder
      setTimeout(() => {
        const ta = bodyRef.current;
        if (!ta) return;
        ta.focus();
        const txt = ta.value;
        const m = txt.match(/\[Sem nap[ií]šte[^\]]*\]/);
        if (m) {
          const start = txt.indexOf(m[0]);
          ta.setSelectionRange(start, start + m[0].length);
        } else {
          ta.setSelectionRange(txt.length, txt.length);
        }
      }, 50);
    })();
  }, [entry.id]);

  async function send() {
    if (!to || !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(to)) {
      notify('error', 'Neplatný e-mail príjemcu.'); return;
    }
    if (!subject.trim()) { notify('error', 'Doplňte predmet.'); return; }
    if (!body.trim())    { notify('error', 'Telo e-mailu je prázdne.'); return; }

    setBusy(true);
    const r = await API.formsReply(entry.id, { to, subject, body_text: body, mark_replied: true });
    setBusy(false);
    if (!r.ok || !r.body.ok) {
      notify('error', r.body?.message || 'Odoslanie zlyhalo.');
      return;
    }
    onSent();
  }

  const ms365Ready = !!draft?.can_send;
  const fieldsCount = (entry.values || []).length;
  const recipientName = draft?.name;

  // Visual style tokens for the composer fields — keeps the form clean and roomy.
  const labelStyle = {
    display:'block', fontSize:11, fontWeight:600, letterSpacing:0.6,
    textTransform:'uppercase', color:'var(--ink-500)', marginBottom:6,
  };
  const inputStyle = {
    width:'100%', height:38, padding:'0 12px', fontSize:14,
    border:'1px solid var(--border-strong)', borderRadius:6, background:'#fff',
    fontFamily:'inherit', color:'var(--ink-900)',
  };

  return (
    <Modal
      title=""
      width={820}
      onClose={busy ? () => {} : onClose}
      footer={(
        <>
          <button className="btn" onClick={() => setShowPreview(p => !p)} disabled={busy || !draft}>
            {showPreview ? '✏ Späť na úpravy' : '👁 Náhľad e-mailu'}
          </button>
          <div style={{flex:1}}/>
          <button className="btn" onClick={onClose} disabled={busy}>Zrušiť</button>
          <button
            className="btn btn-primary"
            onClick={send}
            disabled={busy || !ms365Ready || !draft}
            title={!ms365Ready ? 'Microsoft 365 nie je pripojený v Integráciách' : `Odoslať e-mail z účtu ${draft?.from || ''}`}
            style={{minWidth:180}}
          >
            {busy ? 'Posielam…' : '✉ Odoslať e-mail'}
          </button>
        </>
      )}
    >
      {/* Header strip — title + from sender (replaces the default modal title bar) */}
      <div style={{
        display:'flex', alignItems:'center', gap:14,
        marginBottom:18, paddingBottom:14, borderBottom:'1px solid var(--border)',
      }}>
        <div style={{
          width:40, height:40, borderRadius:'50%', flex:'0 0 40px',
          background:'var(--navy-50, #eff6ff)', color:'var(--navy-700, #1e40af)',
          display:'grid', placeItems:'center', fontSize:18,
        }}>✉</div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:16, fontWeight:600, color:'var(--ink-900)'}}>Odpoveď na formulár</div>
          <div className="small muted" style={{marginTop:2}}>
            {entry.form_title}
            {draft?.from && <> · odosielateľ <b style={{color:'var(--ink-700)'}}>{draft.from}</b></>}
          </div>
        </div>
      </div>

      {!draft && !error && (
        <div style={{padding:'24px 0', textAlign:'center', color:'var(--ink-500)'}}>
          Pripravujem koncept…
        </div>
      )}
      {error && (
        <div style={{padding:'10px 12px', background:'var(--red-50, #fef2f2)', color:'var(--red-700, #b91c1c)', border:'1px solid var(--red-200, #fecaca)', borderRadius:6, fontSize:13}}>
          {error}
        </div>
      )}

      {draft && (
        <>
          {!ms365Ready && (
            <div style={{
              padding:'10px 14px', background:'var(--amber-50, #fffbeb)',
              border:'1px solid var(--amber-200, #fde68a)', borderRadius:6,
              marginBottom:14, fontSize:13,
            }}>
              ⚠️ <b>Microsoft 365 nie je pripojený</b> — odoslanie nebude fungovať.
              Choďte do <a href="#/integrations">Integrácie → Microsoft 365</a> a pripojte účet.
            </div>
          )}

          {showPreview ? (
            <ReplyPreview body={body} entry={entry} from={draft.from}/>
          ) : (
            <>
              {/* Two-column row: Komu + Predmet */}
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14}}>
                <div>
                  <label style={labelStyle}>Komu</label>
                  <input value={to} onChange={e => setTo(e.target.value)} style={inputStyle}/>
                  {recipientName && (
                    <div className="small muted" style={{marginTop:4}}>
                      <span style={{color:'var(--ink-700)'}}>{recipientName}</span> · príjemca z formulára
                    </div>
                  )}
                </div>
                <div>
                  <label style={labelStyle}>Predmet</label>
                  <input value={subject} onChange={e => setSubject(e.target.value)} style={inputStyle}/>
                </div>
              </div>

              {/* Body — bigger textarea, ditches the .input height:30px constraint */}
              <div style={{marginBottom:10}}>
                <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:6}}>
                  <label style={labelStyle}>Telo e-mailu</label>
                  <span className="small muted" style={{fontSize:11}}>{body.length} znakov</span>
                </div>
                <textarea
                  ref={bodyRef}
                  value={body}
                  onChange={e => setBody(e.target.value)}
                  style={{
                    width:'100%', minHeight:300, padding:'14px 16px',
                    fontSize:14, lineHeight:1.65, fontFamily:'inherit',
                    border:'1px solid var(--border-strong)', borderRadius:6,
                    background:'#fff', color:'var(--ink-900)', resize:'vertical',
                  }}
                />
              </div>

              {/* Attachment indicator — single subtle line, not a bulky box */}
              <div style={{
                display:'flex', alignItems:'center', gap:10,
                padding:'10px 12px', borderRadius:6,
                background:'var(--navy-50, #eff6ff)',
                border:'1px solid var(--navy-200, #bfdbfe)',
                fontSize:13,
              }}>
                <span style={{fontSize:16}}>📎</span>
                <div style={{flex:1, minWidth:0}}>
                  <div style={{fontWeight:600, color:'var(--navy-800, #0e2744)'}}>
                    Pôvodný formulár sa automaticky pripojí k mailu
                  </div>
                  <div className="small muted" style={{marginTop:2}}>
                    {fieldsCount} {fieldsCount === 1 ? 'pole' : fieldsCount < 5 ? 'polia' : 'polí'} ·
                    odoslaný {entry.date} · klikni <b>Náhľad e-mailu</b> pre kontrolu výsledku
                  </div>
                </div>
              </div>
            </>
          )}
        </>
      )}
    </Modal>
  );
}

// Live preview that mirrors the server-side renderReplyHtml() output.
function ReplyPreview({ body, entry, from }) {
  const esc = (s) => String(s == null ? '' : s)
    .replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  const bodyHtml = esc(body).replace(/\n/g, '<br>');
  return (
    <div style={{
      maxHeight:'56vh', overflow:'auto',
      border:'1px solid var(--border)', borderRadius:8, background:'#fff',
      padding:'18px 20px', fontFamily:'Arial, sans-serif', color:'#0f172a', fontSize:14, lineHeight:1.6,
    }}>
      <div dangerouslySetInnerHTML={{__html: bodyHtml}}/>
      <div style={{marginTop:24, padding:14, border:'1px solid #e2e8f0', borderRadius:8, background:'#f8fafc'}}>
        <div style={{fontSize:11, color:'#64748b', textTransform:'uppercase', letterSpacing:0.6, fontWeight:600, marginBottom:4}}>
          Pôvodný formulár
        </div>
        <div style={{fontSize:14, fontWeight:600, color:'#0e2744'}}>{entry.form_title}</div>
        <div style={{fontSize:12, color:'#94a3b8', marginBottom:10}}>odoslaný {entry.date}</div>
        <table style={{width:'100%', borderCollapse:'collapse'}}>
          <tbody>
            {(entry.values || []).map((v, i) => (
              <tr key={i}>
                <td style={{padding:'4px 12px 4px 0', color:'#64748b', fontSize:13, whiteSpace:'nowrap', verticalAlign:'top'}}>
                  {v.label || `Pole #${v.field_id}`}
                </td>
                <td style={{padding:'4px 0', fontSize:13, color:'#0f172a', verticalAlign:'top', whiteSpace:'pre-wrap', wordBreak:'break-word'}}>
                  {v.value || '—'}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {from && <div style={{marginTop:20, color:'#64748b', fontSize:12}}>{from} · D&D Energy</div>}
    </div>
  );
}
