// Keynara subpages
const { useState: usS, useEffect: usE } = React;

// ============ HOW IT WORKS PAGE ============
function HowPage({ t, lang, onStart }) {
  return (
    <main style={{ paddingTop: 140 }}>
      <section className="container" style={{ paddingBottom: 64 }}>
        <div className="eyebrow">{t.how_page.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20, maxWidth: 900 }}>{t.how_page.title}</h1>
        <p className="body-lg" style={{ maxWidth: 620, fontSize: 20 }}>{t.how_page.lead}</p>
      </section>
      <HowItWorks t={t} />
      <section className="section">
        <div className="container">
          <SectionHeader eyebrow={lang === 'de' ? 'Unter der Haube' : 'Under the hood'} title={lang === 'de' ? 'Technologie, die versteht.' : 'Technology that understands.'} />
          <div className="tech-grid" style={{ marginTop: 56, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {[
              { n: '01', t: lang === 'de' ? 'LLM-Dialogsystem' : 'LLM dialog system', d: lang === 'de' ? 'Kontextverständnis, adaptive Rückfragen, Multi-Turn-Logik.' : 'Context understanding, adaptive follow-ups, multi-turn logic.' },
              { n: '02', t: lang === 'de' ? 'Matching-Algorithmen' : 'Matching algorithms', d: lang === 'de' ? 'Gewichtete Relevanz-Scores basierend auf Nutzerpräferenzen und Marktdaten.' : 'Weighted relevance scores based on preferences and market data.' },
              { n: '03', t: lang === 'de' ? 'Datenaggregation' : 'Data aggregation', d: lang === 'de' ? 'Echtzeit-Aggregation aus Portalen, Makler-APIs und Marktdaten.' : 'Real-time aggregation from portals, broker APIs and market data.' },
            ].map((x, i) => (
              <div key={i} style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 20, padding: 36 }}>
                <div className="label" style={{ color: 'var(--mint-dark)' }}>{x.n}</div>
                <h3 className="h3" style={{ marginTop: 12, marginBottom: 10 }}>{x.t}</h3>
                <p className="body">{x.d}</p>
              </div>
            ))}
          </div>
        </div>
        <style>{`@media (max-width: 860px) { .tech-grid { grid-template-columns: 1fr !important; } }`}</style>
      </section>
      <FinalCTA t={t} onStart={onStart} />
    </main>
  );
}

// ============ PRICING ============
function PricingPage({ t, onStart }) {
  return (
    <main style={{ paddingTop: 140 }}>
      <section className="container" style={{ paddingBottom: 40 }}>
        <div className="eyebrow">{t.pricing.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20, maxWidth: 900 }}>{t.pricing.title}</h1>
        <p className="body-lg" style={{ maxWidth: 620, fontSize: 20 }}>{t.pricing.lead}</p>
      </section>
      <section className="section">
        <div className="container">
          <div className="plan-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {t.pricing.plans.map((p, i) => (
              <Plan key={i} p={p} onStart={onStart} />
            ))}
          </div>
        </div>
        <style>{`@media (max-width: 900px) { .plan-grid { grid-template-columns: 1fr !important; } }`}</style>
      </section>
    </main>
  );
}

function Plan({ p, onStart }) {
  return (
    <div style={{
      background: p.highlight ? 'var(--navy)' : 'white',
      color: p.highlight ? 'white' : 'var(--navy)',
      border: p.highlight ? '1px solid var(--navy)' : '1px solid var(--line)',
      borderRadius: 24, padding: 40,
      position: 'relative', overflow: 'hidden',
      boxShadow: p.highlight ? '0 24px 60px -20px rgba(26,43,60,0.3)' : 'none',
      transform: p.highlight ? 'translateY(-12px)' : 'none',
    }}>
      {p.highlight && (
        <div style={{
          position: 'absolute', top: 20, right: 20,
          fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase',
          padding: '4px 10px', borderRadius: 999,
          background: 'var(--mint)', color: 'var(--navy)', fontWeight: 600,
        }}>Most popular</div>
      )}
      <div style={{ fontFamily: 'DM Sans', fontSize: 22, fontWeight: 500 }}>{p.name}</div>
      <div style={{ marginTop: 24, display: 'flex', alignItems: 'baseline', gap: 8 }}>
        <span style={{ fontFamily: 'DM Sans', fontSize: 48, fontWeight: 300, letterSpacing: '-0.02em' }}>{p.price}</span>
        <span style={{ fontSize: 13, opacity: 0.6 }}>{p.per}</span>
      </div>
      <p style={{ marginTop: 16, fontSize: 15, lineHeight: 1.5, opacity: p.highlight ? 0.72 : 1, color: p.highlight ? 'rgba(255,255,255,0.8)' : 'var(--slate)', minHeight: 48 }}>{p.d}</p>
      <button onClick={onStart} style={{
        width: '100%', marginTop: 24, padding: '14px 20px',
        borderRadius: 999, fontWeight: 600, fontSize: 13, letterSpacing: '0.08em', textTransform: 'uppercase',
        background: p.highlight ? 'var(--mint)' : 'var(--navy)',
        color: p.highlight ? 'var(--navy)' : 'white',
      }}>{p.cta}</button>
      <ul style={{ marginTop: 32, listStyle: 'none', padding: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {p.features.map((f, j) => (
          <li key={j} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14 }}>
            <span style={{
              width: 20, height: 20, borderRadius: '50%',
              background: p.highlight ? 'rgba(0,201,167,0.2)' : 'var(--mint-soft)',
              color: p.highlight ? 'var(--mint)' : 'var(--mint-dark)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
            }}><Icon.check style={{ width: 12, height: 12 }}/></span>
            {f}
          </li>
        ))}
      </ul>
    </div>
  );
}

// ============ INVESTORS PAGE ============
function InvestorsPage({ t, lang, onStart }) {
  return (
    <main style={{ paddingTop: 140 }}>
      <section className="container" style={{ paddingBottom: 48 }}>
        <div className="eyebrow">{t.investors.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20, maxWidth: 1000 }}>{t.investors.title}</h1>
        <p className="body-lg" style={{ maxWidth: 680, fontSize: 20 }}>{t.investors.lead}</p>
      </section>
      <MarketStats t={t} />
      <section className="section">
        <div className="container">
          <SectionHeader eyebrow={lang === 'de' ? 'Geschäftsmodell' : 'Business model'} title={lang === 'de' ? 'Drei Erlösquellen. Skalierbar.' : 'Three revenue streams. Scalable.'} />
          <div className="biz-grid" style={{ marginTop: 56, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {[
              { tag: 'B2B', n: '01', t: lang === 'de' ? 'Lead-Generierung' : 'Lead generation', d: lang === 'de' ? 'Qualifizierte Käufer- und Mieter-Leads für Makler und Plattformen. CPC/CPL-Basis.' : 'Qualified buyer and renter leads for brokers and platforms. CPC/CPL basis.' },
              { tag: 'B2B', n: '02', t: lang === 'de' ? 'Premium-Platzierungen' : 'Premium placements', d: lang === 'de' ? 'Hervorgehobene Listings für Makler mit Premium-Accounts. Monatsmodell.' : 'Highlighted listings for brokers with premium accounts. Monthly subscription.' },
              { tag: 'B2C', n: '03', t: lang === 'de' ? 'Power-User Subscription' : 'Power-User subscription', d: lang === 'de' ? 'Erweiterte Analyse- und Suchfunktionen für Investoren und Vielsucher.' : 'Advanced analytics and search features for investors and heavy searchers.' },
            ].map((x, i) => (
              <div key={i} style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 20, padding: 36 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
                  <span className="chip chip--mint">{x.tag}</span>
                  <span style={{ fontFamily: 'DM Sans', fontSize: 28, fontWeight: 300, color: 'var(--slate)', opacity: 0.4 }}>{x.n}</span>
                </div>
                <h3 className="h3" style={{ marginBottom: 10 }}>{x.t}</h3>
                <p className="body">{x.d}</p>
              </div>
            ))}
          </div>
          <style>{`@media (max-width: 860px) { .biz-grid { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </section>
      <CompetitiveMatrix t={t} lang={lang} />
      <VisionRoadmap lang={lang} />
      <section className="section">
        <div className="container">
          <div style={{
            display: 'grid', gridTemplateColumns: '1fr auto', gap: 40, alignItems: 'center',
            padding: 48, background: 'var(--navy)', color: 'white', borderRadius: 24,
          }} className="deck-cta">
            <div>
              <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.7)' }}>{lang === 'de' ? 'Investor Relations' : 'Investor Relations'}</div>
              <h3 className="h2" style={{ color: 'white', marginTop: 12 }}>{lang === 'de' ? 'Pitch-Deck und Finanzmodell auf Anfrage.' : 'Pitch deck and financial model on request.'}</h3>
              <p style={{ color: 'rgba(255,255,255,0.7)', marginTop: 12, maxWidth: 500 }}>{lang === 'de' ? 'Wir teilen Details unter NDA. Schreib uns kurz, wer du bist — wir antworten innerhalb von 48 Stunden.' : 'We share details under NDA. Send a short intro — we reply within 48 hours.'}</p>
            </div>
            <a href="mailto:investors@keynara.com" className="btn btn--primary">investors@keynara.com</a>
          </div>
          <style>{`@media (max-width: 700px) { .deck-cta { grid-template-columns: 1fr !important; padding: 32px !important; } }`}</style>
        </div>
      </section>
    </main>
  );
}

function CompetitiveMatrix({ t, lang }) {
  return (
    <section className="section surface-fog">
      <div className="container">
        <SectionHeader eyebrow={lang === 'de' ? 'Wettbewerb' : 'Competitive landscape'} title={lang === 'de' ? 'Weniger Daten. Höhere Präzision.' : 'Less data. Higher precision.'} />
        <div style={{ marginTop: 56, background: 'white', border: '1px solid var(--line)', borderRadius: 20, padding: 48, position: 'relative' }}>
          <svg viewBox="0 0 600 420" style={{ width: '100%', height: 'auto' }}>
            {/* Axes */}
            <g>
              <line x1="60" y1="20" x2="60" y2="380" stroke="#4A6278" strokeWidth="1"/>
              <line x1="60" y1="380" x2="580" y2="380" stroke="#4A6278" strokeWidth="1"/>
              <text x="60" y="14" fontSize="10" fill="#4A6278" fontFamily="Inter" letterSpacing="1">
                {lang === 'de' ? 'RELEVANZ' : 'RELEVANCE'} ↑
              </text>
              <text x="580" y="400" fontSize="10" fill="#4A6278" fontFamily="Inter" textAnchor="end" letterSpacing="1">
                → {lang === 'de' ? 'DATENMENGE' : 'DATA VOLUME'}
              </text>
            </g>
            {/* Quadrant grid */}
            <line x1="320" y1="20" x2="320" y2="380" stroke="#E3E7EC" strokeDasharray="3 3"/>
            <line x1="60" y1="200" x2="580" y2="200" stroke="#E3E7EC" strokeDasharray="3 3"/>
            {/* Competitors */}
            {[
              { x: 500, y: 300, n: 'willhaben', type: 'comp' },
              { x: 540, y: 260, n: 'ImmoScout24', type: 'comp' },
              { x: 480, y: 320, n: 'Idealista', type: 'comp' },
              { x: 460, y: 340, n: 'Immowelt', type: 'comp' },
              { x: 140, y: 150, n: lang === 'de' ? 'Lokale Makler' : 'Local brokers', type: 'comp' },
              { x: 180, y: 240, n: lang === 'de' ? 'Kleine Portale' : 'Small portals', type: 'comp' },
              { x: 420, y: 80, n: 'keynara', type: 'key' },
            ].map((p, i) => (
              <g key={i}>
                <circle cx={p.x} cy={p.y} r={p.type === 'key' ? 14 : 8} fill={p.type === 'key' ? '#00C9A7' : '#1A2B3C'} opacity={p.type === 'key' ? 1 : 0.3}/>
                {p.type === 'key' && (
                  <circle cx={p.x} cy={p.y} r="22" fill="none" stroke="#00C9A7" strokeOpacity="0.3" strokeWidth="1">
                    <animate attributeName="r" values="14;28;14" dur="2.5s" repeatCount="indefinite"/>
                    <animate attributeName="stroke-opacity" values="0.4;0;0.4" dur="2.5s" repeatCount="indefinite"/>
                  </circle>
                )}
                <text x={p.x} y={p.y + (p.type === 'key' ? -22 : -14)} fontSize={p.type === 'key' ? 16 : 12}
                      fill={p.type === 'key' ? '#1A2B3C' : '#4A6278'}
                      fontWeight={p.type === 'key' ? 500 : 400}
                      fontFamily="DM Sans" textAnchor="middle">{p.n}</text>
              </g>
            ))}
            {/* Quadrant labels */}
            <text x="75" y="35" fontSize="9" fill="#4A6278" fontFamily="Inter" letterSpacing="1">{lang === 'de' ? 'WENIG DATEN · HOHE RELEVANZ' : 'LOW DATA · HIGH RELEVANCE'}</text>
            <text x="335" y="35" fontSize="9" fill="#4A6278" fontFamily="Inter" letterSpacing="1">{lang === 'de' ? 'VIEL DATEN · HOHE RELEVANZ' : 'HIGH DATA · HIGH RELEVANCE'}</text>
            <text x="75" y="370" fontSize="9" fill="#4A6278" fontFamily="Inter" letterSpacing="1">{lang === 'de' ? 'WENIG DATEN · GERINGE RELEVANZ' : 'LOW DATA · LOW RELEVANCE'}</text>
            <text x="335" y="370" fontSize="9" fill="#4A6278" fontFamily="Inter" letterSpacing="1">{lang === 'de' ? 'VIEL DATEN · GERINGE RELEVANZ' : 'HIGH DATA · LOW RELEVANCE'}</text>
          </svg>
        </div>
      </div>
    </section>
  );
}

function VisionRoadmap({ lang }) {
  const phases = [
    { n: '01', t: lang === 'de' ? 'Phase 1 · 2026' : 'Phase 1 · 2026', title: lang === 'de' ? 'Immobilien DACH & IT' : 'Real estate DACH & IT', d: lang === 'de' ? 'Marktführer in KI-gestützter Immobiliensuche im deutschsprachigen Raum und Italien.' : 'Leader in AI-powered real-estate search across DACH and Italy.' },
    { n: '02', t: lang === 'de' ? 'Phase 2 · 2027' : 'Phase 2 · 2027', title: lang === 'de' ? 'Finanzierung & Versicherung' : 'Financing & insurance', d: lang === 'de' ? 'Erweiterung auf angrenzende Bereiche: Baufinanzierung und Versicherungsvergleich.' : 'Expansion into adjacent domains: mortgage and insurance comparison.' },
    { n: '03', t: lang === 'de' ? 'Phase 3 · 2028+' : 'Phase 3 · 2028+', title: lang === 'de' ? 'Universeller Agent' : 'Universal agent', d: lang === 'de' ? 'Langfristig: Keynara als Entscheidungs-Agent für große Lebensplanung.' : 'Long-term: Keynara as a decision agent for major life planning.' },
  ];
  return (
    <section className="section surface-navy">
      <div className="container">
        <SectionHeader eyebrow={lang === 'de' ? 'Vision' : 'Vision'} title={lang === 'de' ? 'Der Standard für Entscheidungsfindung.' : 'The standard for decision-making.'} on="dark" />
        <div style={{ marginTop: 64, position: 'relative' }}>
          <div style={{ position: 'absolute', top: 32, left: 32, right: 32, height: 1, background: 'rgba(255,255,255,0.15)' }}/>
          <div className="vision-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, position: 'relative' }}>
            {phases.map((p, i) => (
              <div key={i}>
                <div style={{
                  width: 64, height: 64, borderRadius: '50%', background: 'var(--navy)', border: '1px solid rgba(255,255,255,0.2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'DM Sans', fontSize: 20, fontWeight: 400, color: i === 0 ? 'var(--mint)' : 'rgba(255,255,255,0.7)',
                  position: 'relative', zIndex: 1,
                }}>{p.n}</div>
                <div style={{ marginTop: 24, fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.5)' }}>{p.t}</div>
                <h4 className="h3" style={{ color: 'white', marginTop: 8 }}>{p.title}</h4>
                <p style={{ color: 'rgba(255,255,255,0.7)', marginTop: 12, fontSize: 15, lineHeight: 1.5 }}>{p.d}</p>
              </div>
            ))}
          </div>
          <style>{`@media (max-width: 860px) { .vision-grid { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </div>
    </section>
  );
}

// ============ ABOUT ============
function AboutPage({ t, lang }) {
  const values = [
    { t: lang === 'de' ? 'Präzision' : 'Precision', d: lang === 'de' ? 'Wir liefern gezielte, relevante Ergebnisse. Keine Masse, nur Qualität.' : 'We deliver targeted, relevant results. Not volume — quality.' },
    { t: lang === 'de' ? 'Klarheit' : 'Clarity', d: lang === 'de' ? 'Komplexes wird verständlich. Kein Fachjargon, keine Floskeln.' : 'Complexity made understandable. No jargon, no fluff.' },
    { t: lang === 'de' ? 'Effizienz' : 'Efficiency', d: lang === 'de' ? 'Weniger Aufwand, bessere Entscheidungen. Zeit ist das wertvollste Gut.' : 'Less effort, better decisions. Time is the most valuable asset.' },
    { t: lang === 'de' ? 'Vertrauen' : 'Trust', d: lang === 'de' ? 'Kompetente Begleitung auf dem wichtigsten Weg im Leben.' : 'Competent guidance on the most important journey in life.' },
  ];
  const team = [
    { n: 'Léa Marchetti', r: lang === 'de' ? 'Mitgründerin, CEO' : 'Co-founder, CEO', init: 'LM' },
    { n: 'Jonas Wieland', r: lang === 'de' ? 'Mitgründer, CTO' : 'Co-founder, CTO', init: 'JW' },
    { n: 'Sofia Romano', r: lang === 'de' ? 'Head of Product' : 'Head of Product', init: 'SR' },
    { n: 'Daniel Kofler', r: lang === 'de' ? 'Head of Data' : 'Head of Data', init: 'DK' },
  ];
  return (
    <main style={{ paddingTop: 140 }}>
      <section className="container" style={{ paddingBottom: 48 }}>
        <div className="eyebrow">{t.about.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20, maxWidth: 1000 }}>{t.about.title}</h1>
        <p className="body-lg" style={{ maxWidth: 680, fontSize: 20 }}>{t.about.lead}</p>
      </section>
      <section className="section">
        <div className="container">
          <div className="values-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
            {values.map((v, i) => (
              <div key={i} style={{ borderTop: '1px solid var(--line)', paddingTop: 24 }}>
                <div style={{ fontFamily: 'DM Sans', fontSize: 12, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--mint-dark)' }}>0{i+1}</div>
                <h3 className="h3" style={{ marginTop: 12 }}>{v.t}</h3>
                <p className="body" style={{ marginTop: 12 }}>{v.d}</p>
              </div>
            ))}
          </div>
          <style>{`@media (max-width: 860px) { .values-grid { grid-template-columns: 1fr 1fr !important; } } @media (max-width: 500px) { .values-grid { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </section>
      <section className="section surface-fog">
        <div className="container">
          <SectionHeader eyebrow={lang === 'de' ? 'Team' : 'Team'} title={lang === 'de' ? 'Gebaut von Menschen, die Entscheidungen respektieren.' : 'Built by people who respect decisions.'} />
          <div className="team-grid" style={{ marginTop: 56, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
            {team.map((p, i) => (
              <div key={i} style={{ background: 'white', borderRadius: 16, padding: 28, border: '1px solid var(--line)' }}>
                <div style={{
                  width: '100%', aspectRatio: '1/1', borderRadius: 12, marginBottom: 20,
                  background: 'linear-gradient(135deg, #1A2B3C, #4A6278)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontFamily: 'DM Sans', fontSize: 40, fontWeight: 300, color: 'rgba(255,255,255,0.9)', letterSpacing: '-0.02em',
                  position: 'relative', overflow: 'hidden',
                }}>
                  <div style={{ position: 'absolute', inset: 0, background: 'repeating-linear-gradient(45deg, transparent, transparent 6px, rgba(0,201,167,0.06) 6px, rgba(0,201,167,0.06) 8px)' }}/>
                  <span style={{ position: 'relative', zIndex: 1 }}>{p.init}</span>
                </div>
                <div style={{ fontFamily: 'DM Sans', fontSize: 17, fontWeight: 500 }}>{p.n}</div>
                <div style={{ fontSize: 13, color: 'var(--slate)', marginTop: 4 }}>{p.r}</div>
              </div>
            ))}
          </div>
          <style>{`@media (max-width: 900px) { .team-grid { grid-template-columns: 1fr 1fr !important; } } @media (max-width: 500px) { .team-grid { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </section>
    </main>
  );
}

// ============ BLOG ============
function BlogPage({ t, lang }) {
  return (
    <main style={{ paddingTop: 140 }}>
      <section className="container" style={{ paddingBottom: 48 }}>
        <div className="eyebrow">{t.blog.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20, maxWidth: 1000 }}>{t.blog.title}</h1>
        <p className="body-lg" style={{ maxWidth: 680, fontSize: 20 }}>{t.blog.lead}</p>
      </section>
      <section className="section">
        <div className="container">
          {/* Featured post */}
          <div className="feature-post" style={{
            display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 48,
            padding: 40, background: 'var(--fog-2)', border: '1px solid var(--line)', borderRadius: 24, marginBottom: 64,
          }}>
            <div>
              <span className="chip chip--mint">{t.blog.posts[0].tag}</span>
              <h2 className="h2" style={{ marginTop: 20, marginBottom: 16 }}>{t.blog.posts[0].t}</h2>
              <p className="body-lg" style={{ marginBottom: 24 }}>{t.blog.posts[0].d}</p>
              <div style={{ display: 'flex', gap: 16, fontSize: 13, color: 'var(--slate)', alignItems: 'center' }}>
                <span>{t.blog.posts[0].date}</span>
                <span>·</span>
                <span>{t.blog.posts[0].read}</span>
              </div>
            </div>
            <div style={{
              background: 'var(--navy)', borderRadius: 16, minHeight: 240, position: 'relative', overflow: 'hidden',
            }}>
              <svg width="100%" height="100%" viewBox="0 0 400 240" style={{ position: 'absolute', inset: 0 }}>
                <defs>
                  <pattern id="bp1" width="12" height="12" patternUnits="userSpaceOnUse">
                    <circle cx="6" cy="6" r="1" fill="rgba(255,255,255,0.1)"/>
                  </pattern>
                </defs>
                <rect width="400" height="240" fill="url(#bp1)"/>
                <circle cx="300" cy="120" r="80" fill="none" stroke="rgba(0,201,167,0.3)" strokeWidth="1" strokeDasharray="4 4"/>
                <circle cx="300" cy="120" r="40" fill="rgba(0,201,167,0.1)"/>
                <circle cx="300" cy="120" r="12" fill="#00C9A7"/>
              </svg>
              <div style={{ position: 'absolute', bottom: 16, left: 16, fontFamily: 'DM Sans', color: 'rgba(255,255,255,0.5)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                {lang === 'de' ? 'Featured' : 'Featured'}
              </div>
            </div>
          </div>
          {/* Grid of posts */}
          <div className="post-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {t.blog.posts.slice(1).map((p, i) => (
              <article key={i} style={{
                background: 'white', border: '1px solid var(--line)',
                borderRadius: 16, overflow: 'hidden', display: 'flex', flexDirection: 'column',
              }}>
                <PostCover idx={i} />
                <div style={{ padding: 28, flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 12, color: 'var(--slate)' }}>
                    <span className="chip">{p.tag}</span>
                    <span>{p.date}</span>
                  </div>
                  <h3 className="h3" style={{ marginTop: 16, marginBottom: 12 }}>{p.t}</h3>
                  <p className="body" style={{ fontSize: 14 }}>{p.d}</p>
                  <div style={{ marginTop: 16, fontSize: 12, color: 'var(--slate)' }}>{p.read}</div>
                </div>
              </article>
            ))}
          </div>
          <style>{`
            @media (max-width: 900px) { .feature-post, .post-grid { grid-template-columns: 1fr !important; } }
          `}</style>
        </div>
      </section>
    </main>
  );
}

function PostCover({ idx }) {
  const palettes = [
    ['#EEF1F4', '#1A2B3C', '#00C9A7'],
    ['#1A2B3C', '#FFFFFF', '#00C9A7'],
    ['#00C9A7', '#1A2B3C', '#FFFFFF'],
    ['#EEF1F4', '#4A6278', '#1A2B3C'],
    ['#FFFFFF', '#00C9A7', '#1A2B3C'],
  ];
  const p = palettes[idx % palettes.length];
  const patterns = [
    <g key="g"><circle cx="80" cy="50" r="30" fill={p[2]} opacity="0.15"/><circle cx="200" cy="70" r="20" fill={p[2]}/><line x1="40" y1="110" x2="260" y2="110" stroke={p[1]} strokeOpacity="0.3"/></g>,
    <g key="g"><rect x="40" y="40" width="60" height="60" fill={p[2]}/><rect x="120" y="60" width="40" height="40" fill={p[1]} opacity="0.3"/><rect x="180" y="30" width="80" height="80" fill="none" stroke={p[2]} strokeWidth="1.5"/></g>,
    <g key="g"><path d="M40 100 Q 100 30 160 80 T 260 60" fill="none" stroke={p[1]} strokeWidth="2"/><circle cx="260" cy="60" r="6" fill={p[1]}/></g>,
    <g key="g"><line x1="40" y1="40" x2="260" y2="40" stroke={p[2]} strokeWidth="1"/><line x1="40" y1="70" x2="220" y2="70" stroke={p[2]} strokeWidth="1"/><line x1="40" y1="100" x2="180" y2="100" stroke={p[2]} strokeWidth="1"/><circle cx="40" cy="40" r="4" fill={p[1]}/><circle cx="40" cy="70" r="4" fill={p[1]}/><circle cx="40" cy="100" r="4" fill={p[1]}/></g>,
    <g key="g"><polygon points="150,20 200,110 100,110" fill={p[1]} opacity="0.4"/><polygon points="150,30 190,105 110,105" fill="none" stroke={p[2]} strokeWidth="1.5"/></g>,
  ];
  return (
    <div style={{ height: 160, background: p[0], position: 'relative', overflow: 'hidden' }}>
      <svg viewBox="0 0 300 160" width="100%" height="100%">{patterns[idx % patterns.length]}</svg>
    </div>
  );
}

// ============ CONTACT ============
function ContactPage({ t, lang }) {
  const [sent, setSent] = usS(false);
  const [form, setForm] = usS({ name: '', email: '', org: '', topic: t.contact.topics[0], msg: '' });
  function update(k, v) { setForm(f => ({ ...f, [k]: v })); }

  return (
    <main style={{ paddingTop: 140 }}>
      <section className="container" style={{ paddingBottom: 48 }}>
        <div className="eyebrow">{t.contact.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20 }}>{t.contact.title}</h1>
        <p className="body-lg" style={{ maxWidth: 620, fontSize: 20 }}>{t.contact.lead}</p>
      </section>
      <section className="section">
        <div className="container">
          <div className="contact-grid" style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 64 }}>
            <form onSubmit={(e) => { e.preventDefault(); setSent(true); }}
              style={{ background: 'white', border: '1px solid var(--line)', borderRadius: 20, padding: 40 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
                <Field label={t.contact.fields.name}><input required value={form.name} onChange={e => update('name', e.target.value)} style={inputStyle}/></Field>
                <Field label={t.contact.fields.email}><input type="email" required value={form.email} onChange={e => update('email', e.target.value)} style={inputStyle}/></Field>
              </div>
              <Field label={t.contact.fields.org}><input value={form.org} onChange={e => update('org', e.target.value)} style={inputStyle}/></Field>
              <Field label={t.contact.fields.topic}>
                <select value={form.topic} onChange={e => update('topic', e.target.value)} style={inputStyle}>
                  {t.contact.topics.map(x => <option key={x}>{x}</option>)}
                </select>
              </Field>
              <Field label={t.contact.fields.msg}>
                <textarea required value={form.msg} onChange={e => update('msg', e.target.value)} rows="5" style={{ ...inputStyle, resize: 'vertical', minHeight: 120 }}/>
              </Field>
              <button type="submit" className="btn btn--primary" style={{ marginTop: 8 }}>
                {sent ? (lang === 'de' ? 'Gesendet ✓' : 'Sent ✓') : t.contact.fields.send} {!sent && <Icon.arrow/>}
              </button>
            </form>
            <div>
              <h3 className="h3" style={{ marginBottom: 24 }}>{lang === 'de' ? 'Büros' : 'Offices'}</h3>
              {t.contact.offices.map((o, i) => (
                <div key={i} style={{ padding: '20px 0', borderBottom: '1px solid var(--line)' }}>
                  <div style={{ fontFamily: 'DM Sans', fontSize: 18, fontWeight: 500 }}>{o.city}</div>
                  <div style={{ fontSize: 14, color: 'var(--slate)', marginTop: 4 }}>{o.addr}</div>
                  <a href={`mailto:${o.t}`} style={{ fontSize: 14, color: 'var(--mint-dark)', marginTop: 6, display: 'inline-block' }}>{o.t}</a>
                </div>
              ))}
              <div style={{ marginTop: 32, padding: 24, background: 'var(--fog-2)', borderRadius: 16 }}>
                <div style={{ fontSize: 13, color: 'var(--slate)', marginBottom: 8 }}>{lang === 'de' ? 'Allgemeine Anfragen' : 'General enquiries'}</div>
                <a href="mailto:hello@keynara.com" style={{ fontFamily: 'DM Sans', fontSize: 22, color: 'var(--navy)', fontWeight: 500 }}>hello@keynara.com</a>
              </div>
            </div>
          </div>
          <style>{`@media (max-width: 900px) { .contact-grid { grid-template-columns: 1fr !important; } }`}</style>
        </div>
      </section>
    </main>
  );
}

const inputStyle = {
  width: '100%', padding: '12px 14px', fontFamily: 'inherit', fontSize: 15,
  border: '1px solid var(--line)', borderRadius: 10, background: 'var(--fog-2)',
  color: 'var(--navy)', outline: 'none', transition: 'border-color 160ms',
};

function Field({ label, children }) {
  return (
    <label style={{ display: 'block', marginBottom: 20 }}>
      <div style={{ fontSize: 12, fontWeight: 500, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--slate)', marginBottom: 8 }}>{label}</div>
      {children}
    </label>
  );
}

// ============ AGENT PAGE ============
function AgentPage({ t, lang }) {
  const ta = t.agent;
  // !! WICHTIG: Nach Railway-Deployment diese URL anpassen !!
  const API_URL = "https://web-production-c80b9.up.railway.app";

  const [email, setEmail] = React.useState('');
  const [status, setStatus] = React.useState('idle'); // idle | loading | analysiert | fertig | fehler
  const [statusText, setStatusText] = React.useState('');
  const [jobId, setJobId] = React.useState(null);
  const [kundenName, setKundenName] = React.useState('');
  const [fehler, setFehler] = React.useState('');
  const pollingRef = React.useRef(null);

  async function verarbeiten() {
    if (!email.trim()) { setFehler(lang === 'de' ? 'Bitte E-Mail-Text einfügen.' : 'Please paste an e-mail text.'); return; }
    setFehler(''); setStatus('loading'); setStatusText(ta.status_1);
    try {
      const r = await fetch(API_URL + '/verarbeiten', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const d = await r.json();
      if (d.fehler) { setFehler(d.fehler); setStatus('idle'); return; }
      setJobId(d.job_id);
      startePolling(d.job_id);
    } catch(e) {
      setFehler('Verbindungsfehler: ' + e.message); setStatus('idle');
    }
  }

  function startePolling(id) {
    pollingRef.current = setInterval(async () => {
      try {
        const r = await fetch(API_URL + '/status/' + id);
        const d = await r.json();
        if (d.status === 'analysiert') { setStatus('analysiert'); setStatusText(ta.status_2); }
        else if (d.status === 'fertig') { clearInterval(pollingRef.current); setKundenName(d.name || ''); setStatus('fertig'); }
        else if (d.status === 'fehler') { clearInterval(pollingRef.current); setFehler(d.meldung || 'Fehler'); setStatus('idle'); }
      } catch { clearInterval(pollingRef.current); setFehler('Verbindungsfehler'); setStatus('idle'); }
    }, 2500);
  }

  const safeName = (kundenName || 'angebot').toLowerCase().replace(/\s+/g, '_');

  return (
    <main style={{ paddingTop: 120, paddingBottom: 80 }}>
      {/* Header */}
      <section className="container" style={{ paddingBottom: 48 }}>
        <div className="eyebrow">{ta.eyebrow}</div>
        <h1 className="display" style={{ marginTop: 20, marginBottom: 20, maxWidth: 780 }}>{ta.title}</h1>
        <p className="body-lg" style={{ maxWidth: 620, fontSize: 18 }}>{ta.lead}</p>
      </section>

      {/* Generator Card */}
      <section className="container" style={{ paddingBottom: 64 }}>
        <div style={{
            background: 'white',
            border: '1px solid var(--line)',
            borderRadius: 24,
            padding: '40px',
            maxWidth: 720,
            boxShadow: '0 2px 20px rgba(26,43,60,0.06)',
          }}>
            {/* Label */}
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--slate)', marginBottom: 12 }}>
              {ta.label}
            </div>

            {/* Textarea */}
            <textarea
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder={ta.placeholder}
              rows={9}
              style={{
                width: '100%',
                border: '1px solid var(--line)',
                borderRadius: 12,
                padding: '14px 16px',
                fontFamily: 'inherit',
                fontSize: 14,
                lineHeight: 1.65,
                color: 'var(--navy)',
                background: 'var(--fog-2)',
                resize: 'vertical',
                outline: 'none',
                transition: 'border-color 160ms',
              }}
              onFocus={e => e.target.style.borderColor = 'var(--mint-dark)'}
              onBlur={e => e.target.style.borderColor = 'var(--line)'}
            />

            {/* Button */}
            <button
              onClick={verarbeiten}
              disabled={status === 'loading' || status === 'analysiert'}
              style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
                width: '100%', marginTop: 16, padding: '15px 28px',
                background: (status === 'loading' || status === 'analysiert') ? 'var(--fog)' : 'var(--navy)',
                color: (status === 'loading' || status === 'analysiert') ? 'var(--slate)' : 'white',
                border: 'none', borderRadius: 999,
                fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
                letterSpacing: '0.1em', textTransform: 'uppercase',
                cursor: (status === 'loading' || status === 'analysiert') ? 'not-allowed' : 'pointer',
                transition: 'all 180ms',
              }}
            >
              <Icon.sparkle />
              {ta.btn}
            </button>

            {/* Fehler */}
            {fehler && (
              <div style={{ marginTop: 16, padding: '12px 16px', background: '#fdf4f4', border: '1px solid #f5d6d6', borderRadius: 10, fontSize: 14, color: '#9b3a3a' }}>
                {fehler}
              </div>
            )}

            {/* Ladestatus */}
            {(status === 'loading' || status === 'analysiert') && (
              <div style={{ marginTop: 20, padding: '16px 20px', background: 'var(--fog-2)', border: '1px solid var(--line)', borderRadius: 12, display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{
                  width: 18, height: 18, flexShrink: 0,
                  border: '2.5px solid var(--line)', borderTopColor: 'var(--mint-dark)',
                  borderRadius: '50%',
                  animation: 'spin 0.75s linear infinite',
                }}/>
                <span style={{ fontSize: 14, color: 'var(--slate)' }}>{statusText}</span>
                <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
              </div>
            )}

            {/* Ergebnis */}
            {status === 'fertig' && (
              <div style={{ marginTop: 24 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
                  <div style={{
                    width: 24, height: 24, borderRadius: '50%',
                    background: '#4a7c59', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                  }}>
                    <Icon.check style={{ width: 13, height: 13, stroke: 'white', strokeWidth: 2.5 }} />
                  </div>
                  <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#4a7c59' }}>
                    {ta.ready}
                  </span>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
                  {[['DE','🇩🇪','Deutsch'],['IT','🇮🇹','Italiano'],['EN','🇬🇧','English']].map(([code, flag, label]) => (
                    <a key={code}
                      href={API_URL + '/download/' + jobId + '/' + code}
                      download={`angebot_${safeName}_${code}.txt`}
                      style={{
                        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
                        padding: '18px 12px',
                        border: '1px solid var(--line)', borderRadius: 14,
                        background: 'white', color: 'var(--navy)',
                        textDecoration: 'none',
                        fontSize: 12, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase',
                        transition: 'all 180ms',
                      }}
                      onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--mint-dark)'; e.currentTarget.style.background = 'var(--fog-2)'; }}
                      onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.background = 'white'; }}
                    >
                      <span style={{ fontSize: '1.6rem' }}>{flag}</span>
                      <span>{label}</span>
                    </a>
                  ))}
                </div>
                <div style={{ marginTop: 16, fontSize: 12, color: 'var(--slate)', textAlign: 'center' }}>
                  {ta.note}
                </div>
              </div>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { HowPage, PricingPage, InvestorsPage, AboutPage, BlogPage, ContactPage, AgentPage });
