const { useState: useStateE, useEffect: useEffectE, useRef: useRefE } = React;

function fmtRelE(iso) {
  if (!iso) return '—';
  const diff = Date.now() - new Date(iso).getTime();
  const m = Math.floor(diff / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  return `${Math.floor(h / 24)}d ago`;
}

const FROM_OPTIONS = [
  { value: 'security@pipal.life',  label: 'security@pipal.life' },
  { value: 'hello@pipal.life',     label: 'hello@pipal.life' },
  { value: 'support@pipal.life',   label: 'support@pipal.life' },
  { value: 'noreply@pipal.life',   label: 'noreply@pipal.life' },
];

// ── EmailHistoryTable ─────────────────────────────────────────────────────────

const EmailHistoryTable = ({ history, loading }) => {
  if (loading) return <div style={{ padding: '32px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>Loading…</div>;
  if (!history.length) return <div style={{ padding: '40px', textAlign: 'center', color: 'var(--ink-3)', fontSize: 13 }}>No emails sent yet</div>;

  return (
    <div className="t-wrap">
      <table className="t">
        <thead>
          <tr>
            <th>To</th>
            <th>Subject</th>
            <th>From</th>
            <th>Mode</th>
            <th style={{ textAlign: 'right' }}>Sent</th>
          </tr>
        </thead>
        <tbody>
          {history.map((e, i) => (
            <tr key={i}>
              <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--ink-2)' }}>{e.to}</td>
              <td style={{ fontWeight: 500, fontSize: 13, color: 'var(--ink)', maxWidth: 260 }}>
                <span style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{e.subject}</span>
              </td>
              <td style={{ fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{e.from}</td>
              <td><span className="chip">{e.mode ?? 'text'}</span></td>
              <td style={{ textAlign: 'right', fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', whiteSpace: 'nowrap' }} title={e.sent_at}>{fmtRelE(e.sent_at)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

// ── EmailsPage ────────────────────────────────────────────────────────────────

const EmailsPage = () => {
  const I = window.Icons;

  const [from, setFrom]       = useStateE(FROM_OPTIONS[0].value);
  const [to, setTo]           = useStateE('');
  const [subject, setSubject] = useStateE('');
  const [body, setBody]       = useStateE('');
  const [mode, setMode]       = useStateE('text'); // 'text' | 'html'
  const [showPreview, setShowPreview] = useStateE(false);
  const [sending, setSending] = useStateE(false);
  const [error, setError]     = useStateE(null);
  const [toast, setToast]     = useStateE(null);
  const [history, setHistory] = useStateE([]);
  const [loadingHistory, setLoadingHistory] = useStateE(true);

  const STORAGE_KEY = 'pipal_email_history';

  const showToast = (msg, ok = true) => {
    setToast({ msg, ok });
    setTimeout(() => setToast(null), 3500);
  };

  const loadHistory = () => {
    setLoadingHistory(true);
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      setHistory(raw ? JSON.parse(raw) : []);
    } catch { setHistory([]); }
    setLoadingHistory(false);
  };

  useEffectE(() => { loadHistory(); }, []);

  const saveToHistory = (entry) => {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      const existing = raw ? JSON.parse(raw) : [];
      const updated = [entry, ...existing].slice(0, 100);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
      setHistory(updated);
    } catch {}
  };

  const handleSend = async () => {
    const toTrimmed = to.trim();
    const subjectTrimmed = subject.trim();
    const bodyTrimmed = body.trim();

    if (!toTrimmed)      { setError('Recipient email is required'); return; }
    if (!subjectTrimmed) { setError('Subject is required'); return; }
    if (!bodyTrimmed)    { setError('Body is required'); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(toTrimmed)) {
      setError('Enter a valid recipient email address');
      return;
    }

    setError(null);
    setSending(true);

    try {
      const res = await fetch('/api/email/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ from, to: toTrimmed, subject: subjectTrimmed, body: bodyTrimmed, mode }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? `Server error ${res.status}`);

      saveToHistory({ from, to: toTrimmed, subject: subjectTrimmed, mode, sent_at: new Date().toISOString(), resend_id: data.id });
      showToast(`Email sent to ${toTrimmed}`);
      setTo('');
      setSubject('');
      setBody('');
      setShowPreview(false);
    } catch (err) {
      setError(err.message ?? 'Failed to send');
    } finally {
      setSending(false);
    }
  };

  const isHtml = mode === 'html';

  return (
    <div className="page" data-screen-label="Emails">

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
          zIndex: 200, padding: '10px 18px', borderRadius: 8,
          background: toast.ok ? 'var(--ink)' : 'var(--neg)',
          color: '#fff', fontSize: 13, fontWeight: 500, boxShadow: '0 4px 16px rgba(0,0,0,0.18)',
          pointerEvents: 'none', whiteSpace: 'nowrap',
        }}>{toast.msg}</div>
      )}

      {/* Header */}
      <div className="page-h">
        <div>
          <div className="ts">{history.length} sent · via Resend</div>
          <h1>Emails</h1>
        </div>
      </div>

      {/* Compose panel */}
      <div className="panel" style={{ marginTop: 14, overflow: 'visible' }}>
        <div className="panel-h">
          <I.message size={13} style={{ color: 'var(--ink-3)', marginRight: 6 }} />
          <span>Compose</span>
          {/* Mode toggle */}
          <div style={{ marginLeft: 'auto', display: 'flex', background: 'var(--surface-2)', borderRadius: 6, padding: 2, gap: 2 }}>
            {['text', 'html'].map(m => (
              <button
                key={m}
                onClick={() => { setMode(m); setShowPreview(false); }}
                style={{
                  padding: '3px 10px', borderRadius: 4, fontSize: 11, fontWeight: 500,
                  fontFamily: 'var(--font-mono)', border: 'none', cursor: 'pointer',
                  background: mode === m ? 'var(--surface)' : 'transparent',
                  color: mode === m ? 'var(--ink)' : 'var(--ink-3)',
                  boxShadow: mode === m ? '0 1px 2px rgba(0,0,0,0.08)' : 'none',
                }}
              >{m.toUpperCase()}</button>
            ))}
          </div>
        </div>

        <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* From / To */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>From</div>
              <select
                value={from}
                onChange={e => setFrom(e.target.value)}
                style={{
                  width: '100%', padding: '7px 10px', fontSize: 13, borderRadius: 6,
                  border: '1px solid var(--hairline)', background: 'var(--surface-2)',
                  color: 'var(--ink)', outline: 'none', fontFamily: 'var(--font-mono)', cursor: 'pointer',
                }}
              >
                {FROM_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </div>
            <div>
              <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>To</div>
              <input
                type="email"
                placeholder="recipient@example.com"
                value={to}
                onChange={e => setTo(e.target.value)}
                style={{
                  width: '100%', boxSizing: 'border-box', padding: '7px 10px', fontSize: 13,
                  borderRadius: 6, border: '1px solid var(--hairline)', background: 'var(--surface-2)',
                  color: 'var(--ink)', outline: 'none', fontFamily: 'var(--font-mono)',
                }}
              />
            </div>
          </div>

          {/* Subject */}
          <div>
            <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>Subject</div>
            <input
              type="text"
              placeholder="e.g. Your order has shipped 🎉"
              value={subject}
              onChange={e => setSubject(e.target.value)}
              style={{
                width: '100%', boxSizing: 'border-box', padding: '7px 10px', fontSize: 13,
                borderRadius: 6, border: '1px solid var(--hairline)', background: 'var(--surface-2)',
                color: 'var(--ink)', outline: 'none', fontFamily: 'var(--font-sans)',
              }}
            />
          </div>

          {/* Body + preview side by side in HTML mode */}
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>
                  {isHtml ? 'HTML' : 'Body'}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <span style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>{body.length} chars</span>
                  {isHtml && (
                    <button
                      className="btn"
                      style={{ height: 22, fontSize: 11, padding: '0 8px' }}
                      onClick={() => setShowPreview(v => !v)}
                    >
                      {showPreview ? 'Hide preview' : 'Preview'}
                    </button>
                  )}
                </div>
              </div>
              <textarea
                placeholder={isHtml ? '<!DOCTYPE html>\n<html>…</html>' : 'Write your email here…'}
                value={body}
                onChange={e => setBody(e.target.value)}
                style={{
                  width: '100%', boxSizing: 'border-box', padding: '10px', fontSize: 12.5,
                  borderRadius: 6, border: '1px solid var(--hairline)', background: 'var(--surface-2)',
                  color: 'var(--ink)', outline: 'none',
                  fontFamily: isHtml ? 'var(--font-mono)' : 'var(--font-sans)',
                  resize: 'vertical', minHeight: isHtml ? 320 : 200, lineHeight: 1.6,
                  tabSize: 2,
                }}
                onKeyDown={e => {
                  // Tab inserts spaces in HTML mode instead of jumping focus
                  if (isHtml && e.key === 'Tab') {
                    e.preventDefault();
                    const s = e.target.selectionStart;
                    const v = e.target.value;
                    setBody(v.substring(0, s) + '  ' + v.substring(e.target.selectionEnd));
                    requestAnimationFrame(() => { e.target.selectionStart = e.target.selectionEnd = s + 2; });
                  }
                }}
              />
              {isHtml && (
                <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 5 }}>
                  Paste your full HTML. Click Preview to see it rendered before sending.
                </div>
              )}
            </div>

            {/* Live preview pane */}
            {isHtml && showPreview && body.trim() && (
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-3)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 6 }}>Preview</div>
                <iframe
                  srcDoc={body}
                  sandbox="allow-same-origin"
                  style={{
                    width: '100%', height: 400, borderRadius: 6,
                    border: '1px solid var(--hairline)', background: '#fff',
                  }}
                />
              </div>
            )}
          </div>

          {/* Error */}
          {error && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5, color: 'var(--neg)' }}>
              <I.warn size={13} /> {error}
            </div>
          )}

          {/* Actions */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <button className="btn primary" onClick={handleSend} disabled={sending} style={{ gap: 6 }}>
              <I.message size={12} />
              {sending ? 'Sending…' : 'Send email'}
            </button>
            <button className="btn" onClick={() => { setTo(''); setSubject(''); setBody(''); setError(null); setShowPreview(false); }} disabled={sending}>
              Clear
            </button>
          </div>
        </div>
      </div>

      {/* History */}
      <div className="panel" style={{ marginTop: 14, overflow: 'hidden' }}>
        <div className="panel-h">
          <span>Sent emails</span>
          <button className="btn right" style={{ height: 26, fontSize: 11 }} onClick={loadHistory}>
            <I.refresh size={11} /> Refresh
          </button>
        </div>
        <EmailHistoryTable history={history} loading={loadingHistory} />
      </div>

    </div>
  );
};

window.EmailsPage = EmailsPage;
