/* global React, ArrowUR */
const { useState: useStateB, useEffect: useEffectB, useRef: useRefB } = React;

/* ──────────────────────────────────────────────────────────────
   Packages — 30h / 40h / 60h "auf Anfrage"
   ────────────────────────────────────────────────────────────── */

const PACKAGES = [
  {
    name: 'Boxenstopp',
    hours: 30,
    tagline: 'Der schnelle Boxenstopp im Alltag',
    blurb: 'Für alle, die im Tagesgeschäft regelmäßig Entlastung brauchen. Postfach, Termine und Backoffice übernehme ich.',
    cta: 'Paket anfragen',
    accent: false,
  },
  {
    name: 'Windschatten',
    hours: 40,
    tagline: 'Im Windschatten läuft es leichter',
    blurb: 'Für alle, die mehr abgeben wollen. Genug Zeit für Kundenbetreuung, Vertrieb und deine Kommunikation.',
    cta: 'Paket anfragen',
    accent: true, // recommended
  },
  {
    name: 'Pole Position',
    hours: 60,
    tagline: 'Bester Startplatz für dein Business',
    blurb: 'Für alle, die dauerhaft entlastet sein wollen. Raum für Projekte, Automatisierung und deinen Außenauftritt.',
    cta: 'Paket anfragen',
    accent: false,
  },
];

function Packages() {
  const ref = useRefB(null);
  useEffectB(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add('in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12 });
    el.querySelectorAll('.fade-in').forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);

  return (
    <section id="pakete" ref={ref} style={{ background: 'var(--paper)' }}>
      <div className="shell-wide">
        <div style={{ marginBottom: 40 }}>
          <div className="fade-in">
            <span className="eyebrow">Pakete</span>
            <h2 className="display display-lg" style={{ marginTop: 24 }}>
              Mehr Ordnung.<br />
              <span className="italic">Weniger Chaos.</span>
            </h2>
          </div>
          <p className="fade-in" style={{ fontSize: 17, lineHeight: 1.55, color: 'var(--ink-80)', margin: '20px 0 0', maxWidth: 980 }}>
            Planbare Unterstützung für dein Unternehmen. Wähl das Paket, das zu deinem Bedarf passt.<br />
            Transparent, flexibel und auf langfristige Zusammenarbeit ausgelegt.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0,1fr))', gap: 16 }}>
          {PACKAGES.map((p, i) => (
            <PackageCard key={p.name} pkg={p} />
          ))}
        </div>

        <div className="fade-in" style={{
          marginTop: 16,
          background: 'var(--yellow)',
          borderRadius: 'var(--radius)',
          padding: '26px 32px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: 20,
        }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <span className="mono mono-sm" style={{ color: 'var(--ink-60)' }}>Individuelles Paket</span>
            <p className="display display-sm" style={{ fontSize: 'clamp(20px, 2vw, 30px)', margin: 0, lineHeight: 1.05, fontStretch: '75%', color: 'var(--ink)' }}>
              Brauchst du etwas anderes? <span className="italic">Sprechen wir darüber.</span>
            </p>
          </div>
          <a href="#kontakt" className="btn hero-cta no-wiggle" style={{ background: 'var(--ink)', color: 'var(--cream-soft)', gap: 12 }}>
            Paket besprechen
            <span style={{
              display: 'grid', placeItems: 'center', flexShrink: 0,
              color: 'var(--cream-soft)',
            }}>
              <svg width="18" height="18" viewBox="0 0 14 14" fill="none">
                <path d="M2.5 7H11.5M11.5 7L7.5 3M11.5 7L7.5 11" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
          </a>
        </div>

      </div>
    </section>
  );
}

function PackageCard({ pkg }) {
  const [hovered, setHovered] = useStateB(false);
  const dark = hovered;
  return (
    <article className={`surface ${dark ? 'surface-ink' : ''}`}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        padding: '30px 28px 28px',
        minHeight: 440,
        gap: 14,
        position: 'relative',
        background: dark ? 'var(--ink)' : 'var(--blue)',
        border: '1px solid transparent',
        transform: hovered ? 'translateY(-4px)' : 'translateY(0)',
        transition: 'background .25s ease, transform .25s ease, border-color .25s ease',
        cursor: 'default',
      }}>
      {pkg.accent && (
        <div style={{
          position: 'absolute', top: -12, left: 24,
          padding: '6px 12px', borderRadius: 999,
          background: 'var(--yellow)', color: 'var(--ink)',
          fontFamily: 'var(--f-mono)', fontSize: 11, letterSpacing: '0.06em', textTransform: 'uppercase',
        }}>Empfehlung</div>
      )}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ minWidth: 0 }}>
          <div className="mono mono-sm" style={{ color: dark ? 'rgba(245,240,232,0.6)' : 'var(--ink-60)' }}>
            Paket
          </div>
          <h3 className="display display-md" style={{
            fontSize: 'clamp(24px, 2.8vw, 44px)', marginTop: 6,
            overflowWrap: 'normal', wordBreak: 'keep-all', hyphens: 'none',
            color: dark ? 'var(--cream-soft)' : 'var(--ink)',
            transition: 'color .35s ease',
          }}>{pkg.name}</h3>
        </div>
        <div style={{
          textAlign: 'right',
          padding: '12px 16px',
          borderRadius: 12,
          flexShrink: 0,
          background: 'var(--paper)',
          border: '1px solid var(--ink-15)',
        }}>
          <div className="display" style={{
            fontSize: 36, lineHeight: 1, fontWeight: 600, fontStretch: '75%', whiteSpace: 'nowrap',
            color: 'var(--ink)',
          }}>{pkg.hours}h</div>
          <div className="mono mono-sm" style={{
            marginTop: 4, whiteSpace: 'nowrap',
            color: 'var(--ink-60)',
          }}>pro Monat</div>
        </div>
      </div>

      <p style={{
        fontFamily: 'var(--f-serif)', fontStyle: 'italic', letterSpacing: '-0.04em',
        fontSize: 20, lineHeight: 1.3, margin: '4px 0 0',
        color: dark ? 'var(--yellow)' : 'var(--ink)', transition: 'color .35s ease',
      }}>{pkg.tagline}</p>

      <p style={{
        fontSize: 15, lineHeight: 1.55, margin: '0',
        color: dark ? 'rgba(245,240,232,0.78)' : 'var(--ink-80)',
      }}>{pkg.blurb}</p>

      <ul style={{ listStyle: 'none', padding: 0, margin: '8px 0 0', display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
        {[
          'Individuell anpassbar: Du wählst die Aufgaben, ich kümmere mich darum.',
          'Einmal pro Woche stimmen wir uns in einem einstündigen Check-in-Call ab.',
        ].map((line, i) => (
          <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style={{ flex: '0 0 16px', marginTop: 3, animation: 'spin 14s linear infinite' }}>
              <path d="M12 2 L14.6 8.6 L21.6 9.2 L16.2 13.8 L17.9 20.8 L12 17 L6.1 20.8 L7.8 13.8 L2.4 9.2 L9.4 8.6 Z" fill="var(--yellow)" />
            </svg>
            <span style={{
              fontSize: 15, lineHeight: 1.5,
              color: dark ? 'rgba(245,240,232,0.9)' : 'var(--ink)',
            }}>{line}</span>
          </li>
        ))}
      </ul>
    </article>
  );
}

/* ──────────────────────────────────────────────────────────────
   Quote spotlight
   ────────────────────────────────────────────────────────────── */

function Quote() {
  return (
    <section style={{
      background: 'var(--blue)',
      padding: '120px 0',
    }}>
      <div className="shell" style={{ textAlign: 'center', position: 'relative' }}>
        <div style={{
          position: 'absolute', top: -40, left: '50%', transform: 'translateX(-50%)',
          fontFamily: 'var(--f-serif)', fontSize: 180, lineHeight: 0.6,
          color: 'rgba(15,26,46,0.12)', fontStyle: 'italic',
          pointerEvents: 'none',
        }}>"</div>
        <p className="display" style={{
          fontFamily: 'var(--f-serif)', fontStretch: 'normal', fontWeight: 400,
          fontSize: 'clamp(34px, 5vw, 76px)',
          lineHeight: 1.1, letterSpacing: '-0.04em',
          maxWidth: 1100, margin: '0 auto',
        }}>
          „Mehr Struktur. Weniger Chaos.<br />
          <em style={{ background: 'var(--yellow)', padding: '0 14px', fontStyle: 'italic' }}>Mehr Zeit</em>{' '}
          für <span style={{ fontFamily: 'var(--f-display)', fontStretch: '75%', fontStyle: 'normal', fontWeight: 600 }}>dein Unternehmen</span>."
        </p>
        <div style={{ marginTop: 40, display: 'inline-flex', alignItems: 'center', gap: 12 }}>
          <span style={{ width: 28, height: 1, background: 'var(--ink)' }} />
          <span className="mono mono-sm">Aleksandra, zu jeder Person die fragt was sie eigentlich tut</span>
        </div>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────────────────────
   Contact
   ────────────────────────────────────────────────────────────── */

function Contact() {
  const [form, setForm] = useStateB({ name: '', email: '', company: '', paket: '', timing: '', message: '', website: '' });
  const [submitted, setSubmitted] = useStateB(false);
  const [sending, setSending] = useStateB(false);
  const [error, setError] = useStateB('');
  const ref = useRefB(null);

  useEffectB(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { e.target.classList.add('in'); io.unobserve(e.target); }
      });
    }, { threshold: 0.1 });
    el.querySelectorAll('.fade-in').forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });
  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setSending(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Senden fehlgeschlagen.');
      setSubmitted(true);
    } catch (err) {
      setError(err.message || 'Etwas ist schiefgelaufen. Bitte versuch es erneut oder schreib mir direkt an hi@aleksandrakrajic.com.');
    } finally {
      setSending(false);
    }
  };

  return (
    <section id="kontakt" ref={ref} style={{ background: 'var(--ink)', color: 'var(--cream-soft)', paddingTop: 72, paddingBottom: 72 }}>
      <div className="shell-wide">
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,0.85fr) minmax(0,1.15fr)', gap: 56, alignItems: 'flex-start' }}>

          {/* Left: invitation */}
          <div className="fade-in" style={{ paddingTop: 48 }}>
            <span className="eyebrow" style={{ color: 'rgba(245,240,232,0.7)' }}>
              Kontakt
            </span>
            <h2 className="display display-lg" lang="de" style={{ marginTop: 24, color: 'var(--cream-soft)', overflowWrap: 'normal', hyphens: 'none' }}>
              Starten <span className="italic" style={{ color: 'var(--yellow)' }}>wir</span>.
            </h2>
            <p style={{ fontSize: 17, lineHeight: 1.55, color: 'rgba(245,240,232,0.78)', margin: '20px 0 0', maxWidth: 460, display: 'none' }}>
              Schreib mir kurz, was bei dir gerade liegen bleibt. Ich lese jede
              Anfrage selbst und melde mich innerhalb von 24 Stunden bei dir.
            </p>

            <a href="#anfrage"
               className="btn btn-yellow"
               style={{ marginTop: 32, padding: '18px 28px 19px', fontSize: 15, display: 'none' }}>
              Anfrage senden
              <span className="btn-icon"><ArrowUR /></span>
            </a>

            <ol style={{ listStyle: 'none', padding: 0, margin: '56px 0 0', display: 'flex', flexDirection: 'column', gap: 0, position: 'relative' }}>
              {['Du schreibst mir kurz, was bei dir gerade liegen bleibt.', 'Ich lese deine Anfrage persönlich und melde mich innerhalb von 24 Stunden.', 'In einem 30-minütigen Gespräch klären wir, ob es passt.'].map((it, i, arr) => (
                <li key={it} style={{ display: 'flex', alignItems: 'flex-start', gap: 18, position: 'relative', height: i === arr.length - 1 ? 'auto' : 84 }}>
                  {i !== arr.length - 1 && (
                    <span style={{
                      position: 'absolute', left: 15, top: 32, height: 42, width: 1,
                      background: 'rgba(245,240,232,0.22)',
                    }}></span>
                  )}
                  <span style={{
                    flexShrink: 0, width: 31, height: 31, borderRadius: 999,
                    border: '1px solid var(--yellow)', color: 'var(--yellow)',
                    display: 'grid', placeItems: 'center', position: 'relative', zIndex: 1,
                    background: 'var(--ink)',
                    fontFamily: 'var(--f-mono)', fontSize: 12, fontWeight: 500,
                  }}>{i + 1}</span>
                  <span style={{ fontSize: 17, lineHeight: 1.55, color: 'rgba(245,240,232,0.9)', paddingTop: 3, display: 'block' }}>{it}</span>
                </li>
              ))}
            </ol>
          </div>

          {/* Right: form */}
          <div id="anfrage" className="fade-in" style={{
            background: 'var(--cream-soft)', color: 'var(--ink)',
            borderRadius: 'var(--radius-lg)',
            padding: '32px 40px 32px',
            maxWidth: 620,
            marginTop: 48,
            justifySelf: 'end',
            width: '100%',
          }}>
            {submitted ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 20, minHeight: 480, justifyContent: 'center' }}>
                <div style={{ display: 'inline-block', padding: '8px 14px', background: 'var(--yellow)', borderRadius: 999, alignSelf: 'flex-start' }}>
                  <span className="mono mono-sm">Nachricht angekommen</span>
                </div>
                <h3 className="display display-md" style={{ fontSize: 56 }}>
                  Vielen Dank{form.name ? `, ${form.name.split(' ')[0]}` : ''}.
                </h3>
                <p style={{ fontSize: 17, lineHeight: 1.5, color: 'var(--ink-80)', margin: 0 }}>
                  Deine Anfrage ist bei mir angekommen. Ich prüfe sie persönlich und
                  melde mich innerhalb von 24 Stunden bei dir zurück.
                </p>
              </div>
            ) : (
              <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 26 }}>
                <input
                  type="text"
                  name="website"
                  value={form.website}
                  onChange={update('website')}
                  autoComplete="off"
                  tabIndex={-1}
                  aria-hidden="true"
                  style={{ position: 'absolute', left: -9999, width: 1, height: 1, opacity: 0 }}
                />
                <div style={{ marginBottom: 6 }}>
                  <h3 className="display display-sm" style={{ fontSize: 40 }}>
                    Wobei kann ich dich<br /><span className="italic">entlasten?</span>
                  </h3>
                </div>

                <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 18 }}>
                  <div className="field">
                    <label>Vor- und Nachname</label>
                    <input type="text" value={form.name} onChange={update('name')} required placeholder="" />
                  </div>
                  <div className="field">
                    <label>E-Mail</label>
                    <input type="email" value={form.email} onChange={update('email')} required placeholder="" />
                  </div>
                </div>

                <div className="field">
                  <label>Unternehmen</label>
                  <input type="text" value={form.company} onChange={update('company')} placeholder="" />
                </div>

                <div className="field">
                  <label>Paket</label>
                  <select value={form.paket} onChange={update('paket')} required>
                    <option value="">Bitte wählen</option>
                    <option>Boxenstopp · 30h pro Monat</option>
                    <option>Windschatten · 40h pro Monat</option>
                    <option>Pole Position · 60h pro Monat</option>
                    <option>Individuelles Paket</option>
                  </select>
                </div>

                <div className="field">
                  <label>Gewünschter Start</label>
                  <select value={form.timing} onChange={update('timing')} required>
                    <option value="">Bitte wählen</option>
                    <option>Am liebsten gestern</option>
                    <option>In den nächsten Wochen</option>
                    <option>Im nächsten Monat</option>
                    <option>Nur unverbindlich anfragen</option>
                  </select>
                </div>

                <div className="field">
                  <label>Nachricht</label>
                  <textarea value={form.message} onChange={update('message')} placeholder="Beschreib kurz dein Unternehmen und wobei du Unterstützung benötigst." />
                </div>

                <button type="submit" disabled={sending} className="btn btn-yellow hero-cta" style={{ alignSelf: 'flex-start', marginTop: 16, paddingLeft: 26, paddingRight: 22, gap: 12, opacity: sending ? 0.6 : 1, cursor: sending ? 'default' : 'pointer' }}>
                  {sending ? 'Wird gesendet…' : 'Anfrage senden'}
                  <span style={{
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                    color: 'var(--ink)',
                  }}>
                    <svg width="18" height="18" viewBox="0 0 14 14" fill="none">
                      <path d="M2.5 7H11.5M11.5 7L7.5 3M11.5 7L7.5 11" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
                    </svg>
                  </span>
                </button>
                {error && (
                  <p style={{ fontSize: 13, lineHeight: 1.5, color: '#B3261E', margin: 0, fontFamily: 'var(--f-sans)' }}>
                    {error}
                  </p>
                )}
                <p style={{ fontSize: 12, lineHeight: 1.5, color: 'var(--ink-60)', margin: 0, fontFamily: 'var(--f-sans)' }}>
                  Mit dem Absenden erkläre ich mich mit der Verarbeitung meiner Daten
                  gemäß der <a href="Datenschutz.html" style={{ color: 'var(--ink)', textDecoration: 'underline' }}>Datenschutzerklärung</a> einverstanden.
                </p>
              </form>
            )}
          </div>

        </div>
      </div>
    </section>
  );
}

/* ──────────────────────────────────────────────────────────────
   Footer
   ────────────────────────────────────────────────────────────── */

function Footer() {
  return (
    <footer style={{ background: 'var(--cream)', color: 'var(--ink)', padding: '72px 0 16px' }}>
      <div className="shell-wide">
        {/* Mega type */}
        <div style={{ overflow: 'hidden' }}>
          <h2 className="display" style={{
            fontSize: 'clamp(56px, 13.5vw, 240px)',
            letterSpacing: '-0.03em',
            lineHeight: 1,
            margin: 0,
            whiteSpace: 'nowrap',
            overflow: 'visible',
            paddingBottom: '0.16em',
            marginBottom: '-0.06em',
          }}>
            aleksandra<span className="italic" style={{ color: 'var(--blue-deep)', marginLeft: '0.08em', letterSpacing: '-0.04em' }}>krajic</span>
          </h2>
        </div>

        {/* Legal strip */}
        <div style={{
          marginTop: 10, paddingTop: 12, borderTop: '1px solid var(--ink-15)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          flexWrap: 'wrap', gap: 16,
        }}>
          <span className="mono mono-sm" style={{ color: 'var(--ink-60)' }}>© Aleksandra Krajic</span>
          <div style={{ display: 'flex', gap: 24 }}>
            <a href="Impressum.html" className="mono mono-sm" style={{ color: 'var(--ink-60)', textDecoration: 'none' }}>Impressum</a>
            <a href="Datenschutz.html" className="mono mono-sm" style={{ color: 'var(--ink-60)', textDecoration: 'none' }}>Datenschutz</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Packages, Quote, Contact, Footer });
