/* Sanio Hi-Fi · E-Mails view
 * 4 mail templates rendered two ways:
 *  - "gmail": in a Gmail-like inbox preview (split list + reading pane)
 *  - "plain": as a plain HTML email at 600px width on neutral background
 * Toggle at the top switches between the two.
 */

const { useState: eUseState } = React;

/* ───────── Email content (used in both modes) ───────── */

function MailSignature() {
  return (
    <table cellPadding="0" cellSpacing="0" border="0" style={{ marginTop: 24, borderCollapse: 'collapse' }}>
      <tbody>
        <tr>
          <td style={{ paddingRight: 14, verticalAlign: 'top' }}>
            <div style={{
              width: 48, height: 48, borderRadius: '50%',
              background: 'oklch(0.92 0.02 155)', color: 'var(--accent-ink)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 17,
            }}>FS</div>
          </td>
          <td style={{ verticalAlign: 'top', fontSize: 13, lineHeight: 1.45, color: 'var(--ink)' }}>
            <div style={{ fontWeight: 600 }}>Franziska Seitz</div>
            <div style={{ color: 'var(--ink-soft)' }}>Energieeffizienz-Expertin · dena-gelistet</div>
            <div style={{ color: 'var(--ink-soft)' }}>+49 89 414 13 21 · franziska@energie-seitz.de</div>
            <div style={{ color: 'var(--ink-faint)', fontSize: 11.5, marginTop: 4 }}>BAFA Energieberater Nr. 312-04781</div>
          </td>
        </tr>
      </tbody>
    </table>
  );
}

function CTAButton({ children, href = '#' }) {
  return (
    <a href={href} onClick={(e) => e.preventDefault()} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '12px 22px',
      background: 'var(--accent)',
      color: 'white',
      textDecoration: 'none',
      borderRadius: 10,
      fontSize: 14, fontWeight: 600,
    }}>
      {children}
    </a>
  );
}

/* — Mail 1: Initial after phone call — */
function MailBody1() {
  return (
    <div className="col">
      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 14.5 }}>Hallo Thomas,</p>
      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 14.5 }}>
        vielen Dank für Ihr Interesse an einer Energieberatung. Wie eben im Telefonat besprochen,
        finden Sie unter dem folgenden Link ein kurzes Formular — damit nehme ich Ihre Anfrage
        strukturiert auf und kann Ihnen schnell ein konkretes Angebot machen.
      </p>

      <div style={{ margin: '20px 0 14px', textAlign: 'center' }}>
        <CTAButton>Formular ausfüllen (ca. 4 Min)</CTAButton>
        <div style={{ marginTop: 10, fontSize: 12, fontFamily: 'var(--font-mono)', color: 'var(--ink-faint)' }}>
          sanio.app/f/franziska-seitz/4287
        </div>
      </div>

      <div style={{ background: 'var(--surface-2)', borderRadius: 10, padding: 14, marginBottom: 14, border: '1px solid var(--line)' }}>
        <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 6 }}>Was Sie ungefähr zur Hand haben sollten</div>
        <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13.5, lineHeight: 1.55, color: 'var(--ink-2)' }}>
          <li>Baujahr und Wohnfläche (ungefähr reicht)</li>
          <li>Heizungstyp und Alter</li>
          <li>Optional: Energieausweis, letzte Heizkosten­abrechnung</li>
        </ul>
      </div>

      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 14.5 }}>
        Sollten Sie noch Fragen haben, erreichen Sie mich unter <b>+49 89 414 13 21</b> oder
        antworten Sie einfach auf diese Mail.
      </p>
      <p style={{ margin: 0, lineHeight: 1.55, fontSize: 14.5 }}>Viele Grüße<br />Franziska Seitz</p>

      <MailSignature />
    </div>
  );
}

/* — Mail 2: Confirmation + offer — */
function StatCard({ icon, title, children, accent }) {
  return (
    <td style={{
      verticalAlign: 'top',
      width: '33.33%',
      padding: 8,
    }}>
      <div style={{
        padding: 14,
        background: accent ? 'var(--accent-soft)' : 'var(--surface-2)',
        border: `1px solid ${accent ? 'var(--accent)' : 'var(--line)'}`,
        borderRadius: 10,
        height: '100%',
      }}>
        <div style={{ fontSize: 22, marginBottom: 8 }}>{icon}</div>
        <div style={{ fontWeight: 600, fontSize: 13, marginBottom: 6, color: accent ? 'var(--accent-ink)' : 'var(--ink)' }}>{title}</div>
        <div style={{ fontSize: 12.5, lineHeight: 1.5, color: 'var(--ink-2)' }}>{children}</div>
      </div>
    </td>
  );
}

function MailBody2() {
  return (
    <div className="col">
      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 14.5 }}>Hallo Thomas,</p>
      <p style={{ margin: '0 0 16px', lineHeight: 1.55, fontSize: 14.5 }}>
        vielen Dank für Ihre detaillierten Angaben. Kompakt das Wichtigste auf einen Blick:
      </p>

      <table cellPadding="0" cellSpacing="0" border="0" style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, margin: '0 -8px 14px' }}>
        <tbody><tr>
          <StatCard icon="📋" title="Mein Angebot">
            <b>Angebot_iSFP_Müller.pdf</b><br />
            <span style={{ color: 'var(--ink-faint)' }}>im Anhang · 2 Seiten</span><br /><br />
            Bitte ausdrucken, unterschreiben und zurücksenden.
          </StatCard>
          <StatCard icon="📅" title="Ihr Termin" accent>
            <b>Di 24.06.</b><br />
            14:00 – 15:30<br />
            Leopoldstr. 148<br /><br />
            <a href="#" onClick={(e) => e.preventDefault()} style={{ color: 'var(--accent-ink)', textDecoration: 'underline' }}>+ Kalender</a>
          </StatCard>
          <StatCard icon="📂" title="Vor dem Termin">
            Noch fehlt:<br />
            · Grundriss EG<br />
            · Wartung 2024<br /><br />
            <a href="#" onClick={(e) => e.preventDefault()} style={{ color: 'var(--accent-ink)', textDecoration: 'underline' }}>→ Grundsteine-Portal</a>
          </StatCard>
        </tr></tbody>
      </table>

      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 14.5 }}>
        Bei Fragen: einfach auf diese E-Mail antworten oder unter <b>+49 89 414 13 21</b>
        anrufen.
      </p>
      <p style={{ margin: 0, lineHeight: 1.55, fontSize: 14.5 }}>Bis Dienstag,<br />Franziska Seitz</p>
      <MailSignature />
    </div>
  );
}

/* — Mail 3: Reminder day before — */
function MailBody3() {
  return (
    <div className="col">
      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 14.5 }}>Hallo Thomas,</p>
      <p style={{ margin: '0 0 16px', lineHeight: 1.55, fontSize: 14.5 }}>
        eine kleine Erinnerung an unseren Termin <b>morgen</b>.
      </p>

      <div style={{
        background: 'var(--accent-soft)',
        border: '1px solid var(--accent)',
        borderRadius: 10, padding: 16, marginBottom: 18,
      }}>
        <div className="row middle gap-14">
          <div style={{ width: 70, padding: '8px 0', background: 'var(--surface)', borderRadius: 8, textAlign: 'center', border: '1px solid var(--accent)' }}>
            <div className="micro bold" style={{ color: 'var(--accent-ink)' }}>DI · JUN</div>
            <div style={{ fontSize: 26, fontWeight: 700, lineHeight: 1 }}>24</div>
            <div className="micro">14:00</div>
          </div>
          <div className="col" style={{ lineHeight: 1.3 }}>
            <div className="small bold">Vor-Ort-Termin · 90 Min</div>
            <div className="tiny" style={{ color: 'var(--accent-ink)' }}>Leopoldstr. 148, 80804 München</div>
            <div className="tiny faint">mit Franziska Seitz</div>
          </div>
        </div>
      </div>

      <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 8 }}>Bitte halten Sie bereit:</div>
      <div className="col gap-4" style={{ marginBottom: 18 }}>
        {[
          ['Energieausweis', true],
          ['Heizkostenabrechnung 2024', true],
          ['Grundriss / Baupläne', false],
          ['Schornsteinfeger-Protokoll', false],
        ].map(([t, ok]) => (
          <div key={t} className="row middle gap-8" style={{ fontSize: 13.5 }}>
            {ok ? (
              <Icon name="check" size={14} style={{ color: 'var(--accent)' }} />
            ) : (
              <span style={{ width: 14, height: 14, borderRadius: 50, border: '1.5px solid var(--ink-faint)' }} />
            )}
            <span style={{ color: ok ? 'var(--accent-ink)' : 'var(--ink)' }}>{t}</span>
            {!ok && <span className="tiny faint" style={{ marginLeft: 'auto' }}>fehlt noch</span>}
          </div>
        ))}
      </div>

      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 13.5 }}>
        Fehlt was?{' '}
        <a href="#" onClick={(e) => e.preventDefault()} style={{ color: 'var(--accent-ink)', textDecoration: 'underline' }}>
          Im Grundsteine-Portal hochladen
        </a>{' '}
        — oder einfach morgen mitbringen.
      </p>
      <p style={{ margin: '0 0 14px', lineHeight: 1.55, fontSize: 13.5 }}>
        Verschieben? Anruf an <b>+49 89 414 13 21</b> reicht.
      </p>
      <p style={{ margin: 0, lineHeight: 1.55, fontSize: 13.5 }}>Bis morgen!<br />Franziska</p>
      <MailSignature />
    </div>
  );
}

/* — Mail 4: Internal briefing — */
function MailBody4() {
  return (
    <div className="col">
      <p style={{ margin: '0 0 12px', lineHeight: 1.55, fontSize: 14.5 }}>Hi Franziska,</p>
      <p style={{ margin: '0 0 16px', lineHeight: 1.55, fontSize: 14.5 }}>
        dein nächster Termin ist in <b>1,5 Stunden</b>. Hier kompakt das Wichtigste — alles auch
        im Dashboard verlinkt.
      </p>

      <div style={{
        background: 'var(--accent-soft)',
        border: '1px solid var(--accent)',
        borderRadius: 10, padding: 14, marginBottom: 14,
      }}>
        <div className="row middle gap-14">
          <div style={{ width: 64, padding: '6px 0', background: 'var(--surface)', borderRadius: 8, textAlign: 'center', border: '1px solid var(--accent)' }}>
            <div className="micro bold" style={{ color: 'var(--accent-ink)' }}>DO · JUN</div>
            <div style={{ fontSize: 22, fontWeight: 700, lineHeight: 1 }}>26</div>
            <div className="micro">10:00</div>
          </div>
          <div className="col" style={{ lineHeight: 1.3 }}>
            <div className="small bold">Sabine Wagner · iSFP</div>
            <div className="tiny" style={{ color: 'var(--accent-ink)' }}>Rosenstr. 7, 82256 Fürstenfeldbruck</div>
            <div className="tiny faint">Fahrtzeit ab Büro ~ 38 Min · jetzt los um 09:22</div>
          </div>
        </div>
      </div>

      <table cellPadding="0" cellSpacing="0" border="0" style={{ width: '100%', borderCollapse: 'separate', margin: '0 -8px 14px' }}>
        <tbody><tr>
          <StatCard icon="🏠" title="Gebäude">EFH · BJ 1995<br />168 m² · 1 WE<br />freistehend<br />Selbstnutzer</StatCard>
          <StatCard icon="🔥" title="Heizung">Gas, 14 J. alt<br />~14 800 kWh/J<br />Heizkörper<br />Wunsch: Wärmepumpe</StatCard>
          <StatCard icon="📂" title="Dokumente">✓ Energieausweis<br />✓ Grundriss EG<br />✓ Heizkosten 24<br />○ Schornsteinfeger</StatCard>
        </tr></tbody>
      </table>

      <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 6 }}>Worauf achten</div>
      <ul style={{ margin: '0 0 18px', paddingLeft: 18, fontSize: 13.5, lineHeight: 1.55 }}>
        <li>Wärmepumpen-Eignung prüfen (Vorlauftemperatur, Dämmung Außenwand)</li>
        <li>BAFA-Förderung: Selbstnutzer · 30 % + Klimabonus prüfen</li>
        <li>Kundin hatte am Telefon Bedenken zur Lautstärke der Außeneinheit</li>
      </ul>

      <div className="row gap-8">
        <CTAButton>📍 Route starten</CTAButton>
        <a href="#" onClick={(e) => e.preventDefault()} style={{
          padding: '12px 18px', borderRadius: 10, border: '1px solid var(--line-2)',
          fontSize: 14, fontWeight: 500, color: 'var(--ink)', textDecoration: 'none',
        }}>📞 anrufen</a>
        <a href="#" onClick={(e) => e.preventDefault()} style={{
          padding: '12px 18px', borderRadius: 10, border: '1px solid var(--line-2)',
          fontSize: 14, fontWeight: 500, color: 'var(--ink)', textDecoration: 'none',
        }}>📋 Lead im Dashboard</a>
      </div>

      <p style={{ marginTop: 22, marginBottom: 0, fontSize: 12, color: 'var(--ink-faint)', lineHeight: 1.5 }}>
        Diese Briefing-Mail wird automatisch 1–2 Stunden vor jedem Vor-Ort-Termin an die
        zugewiesene Beraterin / den zugewiesenen Berater verschickt.
      </p>
    </div>
  );
}

/* ───────── List of mails (used by both modes) ───────── */
const MAILS = [
  {
    id: 1,
    direction: 'out',
    from: 'Franziska Seitz', fromEmail: 'franziska@energie-seitz.de',
    to: 'thomas.mueller@beispiel.de',
    subject: 'Ihre Energieberatung-Anfrage bei Franziska Seitz',
    preview: 'vielen Dank für Ihr Interesse an einer Energieberatung. Wie eben im Telefonat besprochen…',
    sent: 'Di 23.6  ·  14:32',
    sentShort: '14:32',
    tag: { l: 'Initial · automatisch', c: 'accent' },
    body: <MailBody1 />,
  },
  {
    id: 2,
    direction: 'out',
    from: 'Franziska Seitz', fromEmail: 'franziska@energie-seitz.de',
    to: 'thomas.mueller@beispiel.de',
    subject: 'Ihr Angebot und Termin · Energieberatung Franziska Seitz',
    preview: 'vielen Dank für Ihre detaillierten Angaben. Sie finden hier kompakt das Wichtigste…',
    sent: 'Di 23.6  ·  14:37',
    sentShort: '14:37',
    tag: { l: 'Bestätigung · nach Formular', c: 'accent' },
    body: <MailBody2 />,
  },
  {
    id: 3,
    direction: 'out',
    from: 'Franziska Seitz', fromEmail: 'franziska@energie-seitz.de',
    to: 'thomas.mueller@beispiel.de',
    subject: 'Erinnerung: Vor-Ort-Termin morgen um 14:00',
    preview: 'eine kleine Erinnerung an unseren Termin morgen.',
    sent: 'Mo 23.6  ·  09:00',
    sentShort: 'Mo',
    tag: { l: 'Reminder · 1 Tag vor Termin', c: 'warn' },
    body: <MailBody3 />,
  },
  {
    id: 4,
    direction: 'in',
    from: 'Sanio Assistent', fromEmail: 'briefing@sanio.app',
    to: 'franziska@energie-seitz.de',
    subject: '🗂 Briefing 10:00 · Sabine Wagner · Rosenstr. 7, FFB',
    preview: 'dein nächster Termin ist in 1,5 Stunden. Hier kompakt das Wichtigste…',
    sent: 'Do 26.6  ·  08:30',
    sentShort: '08:30',
    tag: { l: 'Briefing · intern · 1–2 h vorher', c: 'info' },
    internal: true,
    body: <MailBody4 />,
  },
];

/* ───────── Gmail-style view ───────── */
function GmailRow({ mail, active, onPick }) {
  const isInternal = mail.internal;
  return (
    <button
      onClick={onPick}
      style={{
        textAlign: 'left',
        display: 'flex', gap: 10,
        padding: '10px 16px',
        borderBottom: '1px solid var(--line)',
        background: active ? 'var(--surface-3)' : 'var(--surface)',
        borderLeft: `3px solid ${active ? 'var(--accent)' : 'transparent'}`,
        cursor: 'pointer',
        width: '100%',
        alignItems: 'flex-start',
      }}
      onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--surface-2)'; }}
      onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'var(--surface)'; }}
    >
      <div className="avatar sm" style={{
        background: isInternal ? 'oklch(0.92 0.02 250)' : 'oklch(0.92 0.02 155)',
        color: isInternal ? 'oklch(0.36 0.09 250)' : 'var(--accent-ink)',
      }}>
        {isInternal ? <Icon name="bolt" size={12} /> : 'FS'}
      </div>
      <div className="col grow" style={{ minWidth: 0 }}>
        <div className="row middle between" style={{ marginBottom: 1 }}>
          <span className="small bold" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {isInternal ? mail.from : `An: ${mail.to.split('@')[0]}…`}
          </span>
          <span className="tiny faint" style={{ flexShrink: 0, marginLeft: 6 }}>{mail.sentShort}</span>
        </div>
        <div className="small" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginBottom: 2 }}>
          {mail.subject}
        </div>
        <div className="tiny faint" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {mail.preview}
        </div>
        <div className="row gap-4" style={{ marginTop: 6 }}>
          <span className={`pill ${mail.tag.c === 'accent' ? 'accent' : mail.tag.c === 'warn' ? 'warn' : 'info'}`} style={{ fontSize: 10.5, height: 18, padding: '0 6px' }}>
            {mail.tag.l}
          </span>
        </div>
      </div>
    </button>
  );
}

function GmailReader({ mail }) {
  if (!mail) return null;
  return (
    <div className="col" style={{ flex: 1, minWidth: 0, background: 'var(--surface)' }}>
      <div style={{ padding: '12px 22px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
        <Icon name="archive" size={16} style={{ color: 'var(--ink-soft)' }} />
        <Icon name="trash" size={16} style={{ color: 'var(--ink-soft)' }} />
        <Icon name="mail" size={16} style={{ color: 'var(--ink-soft)' }} />
        <div style={{ width: 1, height: 18, background: 'var(--line-2)', margin: '0 4px' }} />
        <span className="tiny faint">{mail.tag.l}</span>
        <span className="grow" />
        <Icon name="print" size={16} style={{ color: 'var(--ink-soft)' }} />
        <Icon name="moreV" size={16} style={{ color: 'var(--ink-soft)' }} />
      </div>

      <div className="scroll-y" style={{ flex: 1 }}>
        <div style={{ padding: '20px 28px 28px' }}>
          <div className="h-1" style={{ marginBottom: 16 }}>{mail.subject}</div>

          <div className="row middle gap-12" style={{ marginBottom: 22 }}>
            <div className="avatar lg">FS</div>
            <div className="col grow" style={{ lineHeight: 1.3 }}>
              <div className="row middle gap-6">
                <span className="bold">{mail.from}</span>
                <span className="tiny faint">&lt;{mail.fromEmail}&gt;</span>
              </div>
              <div className="tiny faint">an {mail.to}</div>
            </div>
            <div className="col" style={{ textAlign: 'right', lineHeight: 1.2 }}>
              <div className="small">{mail.sent}</div>
              <div className="row gap-2" style={{ marginTop: 4, justifyContent: 'flex-end' }}>
                <button className="btn icon ghost sm" title="Antworten"><Icon name="reply2" size={14} /></button>
                <button className="btn icon ghost sm" title="Weiterleiten"><Icon name="forward" size={14} /></button>
              </div>
            </div>
          </div>

          {mail.body}

          {/* powered by */}
          <div style={{ marginTop: 28, paddingTop: 14, borderTop: '1px dashed var(--line-2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: 'var(--ink-faint)' }}>
            <span>Energieberatung Franziska Seitz · Leopoldstr. 12, München · USt 143/…/2891</span>
            <span style={{ opacity: 0.75 }}>↳ powered by <b style={{ color: 'var(--accent-ink)' }}>Sanio</b></span>
          </div>
        </div>

        <div style={{ padding: '0 28px 28px' }}>
          <div className="row gap-8">
            <button className="btn"><Icon name="reply2" size={14} /> Antworten</button>
            <button className="btn"><Icon name="forward" size={14} /> Weiterleiten</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function GmailFrame({ active, onPick }) {
  return (
    <div className="browser" style={{ height: 'min(80vh, 820px)' }}>
      <div className="browser-chrome">
        <div className="browser-dots"><span /><span /><span /></div>
        <div className="browser-url"><Icon name="globe" size={11} />mail.google.com/inbox</div>
        <span style={{ width: 70 }} />
      </div>

      <div className="browser-body" style={{ flexDirection: 'row' }}>
        {/* gmail side nav stub */}
        <div className="col" style={{ width: 200, borderRight: '1px solid var(--line)', background: 'var(--surface)', padding: '14px 12px' }}>
          <button className="btn accent" style={{ height: 42, gap: 8, justifyContent: 'flex-start', padding: '0 14px', marginBottom: 14 }}>
            <Icon name="edit" size={14} /> Schreiben
          </button>
          {[
            ['Posteingang', 'inbox', 4, true],
            ['Markiert',    'star',  null, false],
            ['Gesendet',    'send',  null, false],
            ['Entwürfe',    'doc',   1, false],
            ['Wichtig',     'bell',  null, false],
            ['Papierkorb',  'trash', null, false],
          ].map(([t, i, n, on]) => (
            <div key={t} className="row middle gap-8" style={{
              padding: '6px 10px', borderRadius: 999,
              background: on ? 'oklch(0.94 0.04 80)' : 'transparent',
              fontSize: 13, fontWeight: on ? 600 : 500,
              color: 'var(--ink-2)',
            }}>
              <Icon name={i} size={14} />
              <span className="grow">{t}</span>
              {n != null && <span className="tiny bold">{n}</span>}
            </div>
          ))}

          <div className="divider" />

          <div className="eyebrow" style={{ marginBottom: 6 }}>Labels</div>
          <div className="col gap-4">
            {[['Sanio', 'var(--accent)'], ['Kunden', 'oklch(0.7 0.13 250)'], ['Briefing', 'oklch(0.7 0.13 50)']].map(([t, c]) => (
              <div key={t} className="row middle gap-8 small" style={{ padding: '4px 10px' }}>
                <span style={{ width: 10, height: 10, borderRadius: 3, background: c }} />
                {t}
              </div>
            ))}
          </div>
        </div>

        {/* mail list */}
        <div className="col" style={{ width: 380, borderRight: '1px solid var(--line)', background: 'var(--surface)' }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="search" size={14} style={{ color: 'var(--ink-faint)' }} />
            <span className="small muted">Suche · in:Sanio</span>
            <span className="grow" />
            <span className="tiny faint">4 Mails</span>
          </div>
          <div className="scroll-y" style={{ flex: 1 }}>
            {MAILS.map((m) => (
              <GmailRow key={m.id} mail={m} active={active === m.id} onPick={() => onPick(m.id)} />
            ))}
          </div>
        </div>

        {/* reader */}
        <GmailReader mail={MAILS.find((m) => m.id === active)} />
      </div>
    </div>
  );
}

/* ───────── Plain mail view ───────── */
function PlainMail({ mail, onPick }) {
  return (
    <div style={{
      background: 'var(--surface)',
      border: '1px solid var(--line)',
      borderRadius: 14,
      overflow: 'hidden',
      boxShadow: 'var(--shadow-md)',
    }}>
      <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)', background: 'var(--surface-2)' }}>
        <div className="row gap-10" style={{ alignItems: 'flex-start' }}>
          <div className="avatar" style={{ flexShrink: 0 }}>FS</div>
          <div className="col grow" style={{ minWidth: 0, lineHeight: 1.3 }}>
            <div className="small bold" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {mail.from} <span className="tiny faint" style={{ fontWeight: 400 }}>&lt;{mail.fromEmail}&gt;</span>
            </div>
            <div className="tiny faint" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              an {mail.to}
            </div>
            <div className="tiny faint" style={{ marginTop: 2 }}>{mail.sent}</div>
          </div>
          <span className={`pill ${mail.tag.c === 'accent' ? 'accent' : mail.tag.c === 'warn' ? 'warn' : 'info'}`} style={{ fontSize: 10.5, height: 20, flexShrink: 0 }}>
            {mail.tag.l}
          </span>
        </div>
      </div>
      <div style={{ padding: '14px 24px 8px', borderBottom: '1px dashed var(--line-2)' }}>
        <div className="tiny faint">Betreff</div>
        <div className="h-3">{mail.subject}</div>
      </div>
      <div style={{ padding: '20px 24px 22px' }}>
        {mail.body}
      </div>
      <div style={{ padding: '12px 24px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: 'var(--ink-faint)', background: 'var(--surface-2)' }}>
        <span>Energieberatung Franziska Seitz · Leopoldstr. 12, München · USt 143/…/2891</span>
        <span style={{ opacity: 0.75 }}>↳ powered by <b style={{ color: 'var(--accent-ink)' }}>Sanio</b></span>
      </div>
    </div>
  );
}

function PlainFrame({ active, onPick }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr', gap: 24 }}>
      <div className="col gap-8" style={{ position: 'sticky', top: 84, alignSelf: 'flex-start' }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>4 Templates</div>
        {MAILS.map((m) => (
          <button
            key={m.id}
            onClick={() => onPick(m.id)}
            style={{
              textAlign: 'left',
              padding: 12,
              borderRadius: 10,
              background: active === m.id ? 'var(--surface)' : 'transparent',
              border: `1.5px solid ${active === m.id ? 'var(--ink)' : 'var(--line)'}`,
              boxShadow: active === m.id ? 'var(--shadow-sm)' : 'none',
              cursor: 'pointer',
            }}
          >
            <div className="row middle between" style={{ marginBottom: 4 }}>
              <span className="mono micro" style={{ color: 'var(--ink-faint)' }}>0{m.id}</span>
              <span className={`pill ${m.tag.c === 'accent' ? 'accent' : m.tag.c === 'warn' ? 'warn' : 'info'}`} style={{ fontSize: 10, height: 16, padding: '0 6px' }}>
                {m.internal ? 'intern' : 'an Kunde'}
              </span>
            </div>
            <div className="small bold" style={{ marginBottom: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.subject}</div>
            <div className="tiny faint">{m.tag.l}</div>
          </button>
        ))}
      </div>

      <div style={{ maxWidth: 680 }}>
        <PlainMail mail={MAILS.find((m) => m.id === active)} />
      </div>
    </div>
  );
}

/* ───────── Emails container ───────── */
function EmailsView() {
  const [mode, setMode] = eUseState('gmail'); // 'gmail' | 'plain'
  const [active, setActive] = eUseState(2);

  return (
    <div className="fade-up" style={{ minHeight: 'calc(100vh - 60px)', background: 'var(--bg)', padding: '32px 24px 56px' }}>
      <div style={{ maxWidth: 1400, margin: '0 auto' }}>
        <div className="row middle between" style={{ marginBottom: 16 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 4 }}>Auto-E-Mails</div>
            <div className="h-1">4 Templates, die Sanio im Namen der Beraterin schickt.</div>
            <div className="small muted" style={{ marginTop: 4, maxWidth: 620 }}>
              Drei gehen an den Kunden, eine ist ein internes Briefing 1–2 h vor dem Vor-Ort-Termin.
            </div>
          </div>
          <div className="row" style={{ background: 'var(--surface-2)', borderRadius: 10, padding: 3, border: '1px solid var(--line)' }}>
            <button onClick={() => setMode('gmail')} style={{
              height: 32, padding: '0 14px', borderRadius: 7, fontSize: 13, fontWeight: 600,
              background: mode === 'gmail' ? 'var(--surface)' : 'transparent',
              color: mode === 'gmail' ? 'var(--ink)' : 'var(--ink-soft)',
              boxShadow: mode === 'gmail' ? 'var(--shadow-sm)' : 'none',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="inbox" size={13} /> Gmail-Preview
            </button>
            <button onClick={() => setMode('plain')} style={{
              height: 32, padding: '0 14px', borderRadius: 7, fontSize: 13, fontWeight: 600,
              background: mode === 'plain' ? 'var(--surface)' : 'transparent',
              color: mode === 'plain' ? 'var(--ink)' : 'var(--ink-soft)',
              boxShadow: mode === 'plain' ? 'var(--shadow-sm)' : 'none',
              display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
              <Icon name="doc" size={13} /> Reinform
            </button>
          </div>
        </div>

        {mode === 'gmail' ? <GmailFrame active={active} onPick={setActive} /> : <PlainFrame active={active} onPick={setActive} />}
      </div>
    </div>
  );
}

window.EmailsView = EmailsView;
