// Quick City — Career pages (Landing, Jobs list, Job detail)
const { useState: useSC, useEffect: useEC } = React;

// ─────────────────────────────────────────────────────────────────────
// Shared form field
// ─────────────────────────────────────────────────────────────────────
function CField({ label, name, type='text', textarea, required, accept, multiple, hint }) {
  return (
    <div style={{marginBottom:16}}>
      <label style={{display:'block', fontSize:12, fontWeight:600, letterSpacing:'0.04em', color:'#555', marginBottom:6, textTransform:'uppercase'}}>{label}</label>
      {textarea
        ? <textarea name={name} required={required} style={{width:'100%', padding:'12px 14px', border:'1px solid #ddd', borderRadius:4, fontSize:14, fontFamily:'inherit', minHeight:110, resize:'vertical'}} />
        : <input type={type} name={name} required={required} accept={accept} multiple={multiple} style={{width:'100%', padding:'12px 14px', border:'1px solid #ddd', borderRadius:4, fontSize:14, fontFamily:'inherit'}} />}
      {hint && <div style={{fontSize:11, color:'#999', marginTop:5, lineHeight:1.45}}>{hint}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Career landing page — /ifm/karriere, /lns/karriere
// ─────────────────────────────────────────────────────────────────────
function CareerLanding({ brand }) {
  const { lang } = useT();
  const tc = (s) => window.QC_TC ? window.QC_TC(s, lang) : s;
  const data = window.QC_pickCareer ? window.QC_pickCareer(brand, lang) : window.CAREER_DATA[brand];
  const b = window.QC_DATA.brands[brand];
  const stellenHref = `/${brand}/karriere/stellen`;

  // Merge "why" + top benefits into a single 4-item list — pick the strongest
  const reasons = [...data.why.points.slice(0, 4)];

  return (
    <Layout brand={brand}>
      {/* Hero with inline stats */}
      <section className="hero" style={{paddingBottom: 32}}>
        <div className="container">
          <div className="hero__eyebrow">{data.hero.eyebrow}</div>
          <h1 dangerouslySetInnerHTML={{__html: data.hero.title.replace(' ', '<br/>')}} />
          <p style={{maxWidth: 620}}>{data.hero.sub}</p>
          <div className="hero__ctas">
            <a className="btn btn--primary" href={stellenHref}>{data.jobs.length} {tc('offene Stellen ansehen')}</a>
            <a className="btn btn--ghost" href={`${stellenHref}?init=1`}>{tc('Initiativbewerbung')}</a>
          </div>
          <div style={{display:'flex', gap:48, marginTop:48, paddingTop:32, borderTop:'1px solid #eee', flexWrap:'wrap'}}>
            {data.stats.map(s => (
              <div key={s.label}>
                <div style={{fontSize:34, fontWeight:700, color:'var(--accent)', letterSpacing:'-0.02em', lineHeight:1}}><AnimatedNumber value={s.num} /></div>
                <div style={{fontSize:12, letterSpacing:'0.14em', textTransform:'uppercase', color:'#888', fontWeight:600, marginTop:6}}>{tc(s.label)}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Why us — kompakt: 4 Gründe + 4 Benefits-Zeile */}
      <section className="section section--alt">
        <div className="container">
          <div className="section__h">{tc('Warum bei uns')}</div>
          <h2 className="section__title" style={{marginBottom:8}}>{data.why.title}</h2>
          <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(260px, 1fr))', gap:20, marginTop:32}}>
            {reasons.map((p, i) => (
              <div key={i} style={{padding:'20px 22px', background:'#fff', borderLeft:'3px solid var(--accent)'}}>
                <div style={{fontSize:15, fontWeight:700, marginBottom:6, lineHeight:1.3}}>{p.h}</div>
                <div style={{fontSize:13.5, color:'#555', lineHeight:1.55}}>{p.t}</div>
              </div>
            ))}
          </div>

          {/* Inline benefits row */}
          <div style={{display:'flex', gap:14, flexWrap:'wrap', marginTop:32, paddingTop:24, borderTop:'1px solid #e0e0e0'}}>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.16em', textTransform:'uppercase', color:'#888', flex:'1 0 100%', marginBottom:4}}>Außerdem im Paket</div>
            {data.benefits.map((bn, i) => (
              <span key={i} style={{fontSize:13, color:'#333', padding:'8px 14px', background:'#fff', border:'1px solid #e0e0e0', borderRadius:20}}>
                <strong style={{color:'#1a1a1a'}}>✓ {bn.t}</strong>
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* Bewerbungsprozess — kompakt als horizontale Zeile */}
      <section className="section" style={{paddingTop:64, paddingBottom:64}}>
        <div className="container">
          <div className="section__h">{tc('Bewerbungsprozess')}</div>
          <h2 className="section__title" style={{marginBottom:32}}>{tc("So läuft's bei uns ab.")}</h2>
          <div className="career-process" style={{display:'grid', gridTemplateColumns:`repeat(${data.process.length}, 1fr)`, gap:0, position:'relative'}}>
            {/* Connector line */}
            <div style={{position:'absolute', top:20, left:`${100/(data.process.length*2)}%`, right:`${100/(data.process.length*2)}%`, height:2, background:'#e0e0e0', zIndex:0}}></div>
            {data.process.map((p, i) => (
              <div key={i} style={{textAlign:'center', position:'relative', zIndex:1, padding:'0 10px'}}>
                <div style={{width:40, height:40, borderRadius:'50%', background:'var(--accent)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, fontWeight:700, margin:'0 auto 14px', border:'4px solid var(--paper, #fafafa)'}}>{p.n}</div>
                <div style={{fontSize:14, fontWeight:700, marginBottom:6, lineHeight:1.3}}>{p.h}</div>
                <div style={{fontSize:12, color:'#666', lineHeight:1.55}}>{p.t}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA + FAQ in einer Sektion */}
      <section className="section section--alt">
        <div className="container career-cta-grid" style={{display:'grid', gridTemplateColumns:'1fr 1.4fr', gap:64, alignItems:'start'}}>
          <div style={{position:'sticky', top:100}}>
            <div className="section__h">{tc('Loslegen')}</div>
            <h2 style={{fontSize:'clamp(26px, 3.5vw, 40px)', fontWeight:600, lineHeight:1.15, marginBottom:18, letterSpacing:'-0.01em'}}>{tc('Bereit für den')}<br/>{tc('nächsten Schritt?')}</h2>
            <p style={{fontSize:15, color:'#555', lineHeight:1.6, marginBottom:24}}>{data.jobs.length} {tc('offene Positionen — vom Bauleiter bis zur Auszubildenden.')}</p>
            <a className="btn btn--primary" href={stellenHref}>{tc('Alle Stellen ansehen →')}</a>
          </div>
          <div>
            <div className="section__h">{tc('FAQ')}</div>
            <h2 style={{fontSize:'clamp(22px, 2.8vw, 32px)', fontWeight:600, marginBottom:20, letterSpacing:'-0.01em'}}>{tc('Häufige Fragen.')}</h2>
            <div>
              {data.faq.map((f, i) => <FAQItem key={i} q={f.q} a={f.a} />)}
            </div>
          </div>
        </div>
      </section>

      <style>{`
        @media (max-width: 800px) {
          .career-cta-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </Layout>
  );
}

function FAQItem({ q, a }) {
  const [open, setOpen] = useSC(false);
  return (
    <div style={{borderTop:'1px solid #ececec', padding:'20px 0'}}>
      <button onClick={()=>setOpen(o=>!o)} style={{width:'100%', background:'none', border:'none', textAlign:'left', cursor:'pointer', display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:16, padding:0, fontFamily:'inherit'}}>
        <span style={{fontSize:17, fontWeight:600, color:'#1a1a1a', lineHeight:1.4}}>{q}</span>
        <span style={{fontSize:22, color:'var(--accent)', flexShrink:0, transform: open?'rotate(45deg)':'none', transition:'transform 0.2s'}}>+</span>
      </button>
      {open && <div style={{fontSize:15, color:'#555', lineHeight:1.7, marginTop:14, paddingRight:32}}>{a}</div>}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Jobs list page — /:brand/karriere/stellen
// ─────────────────────────────────────────────────────────────────────
function JobsPage({ brand }) {
  const { lang } = useT();
  const tc = (s) => window.QC_TC ? window.QC_TC(s, lang) : s;
  const data = window.QC_pickCareer ? window.QC_pickCareer(brand, lang) : window.CAREER_DATA[brand];
  const b = window.QC_DATA.brands[brand];

  // Read ?init=1 for initiative-application mode
  const initParam = (typeof window !== 'undefined' && window.location.hash.includes('init=1'));

  const [activeType, setType] = useSC('all');
  const [activeSchedule, setSch] = useSC('all');
  const [showInit, setShowInit] = useSC(initParam);
  const [submitted, setSubmitted] = useSC(false);

  const types = [...new Set(data.jobs.map(j => j.type))];
  const schedules = [...new Set(data.jobs.map(j => j.schedule))];

  const list = data.jobs.filter(j =>
    (activeType === 'all' || j.type === activeType) &&
    (activeSchedule === 'all' || j.schedule === activeSchedule)
  );

  return (
    <Layout brand={brand}>
      <section className="hero" style={{paddingBottom:48}}>
        <div className="container">
          <div className="hero__eyebrow">
            <a href={`/${brand}/karriere`} style={{color:'inherit', textDecoration:'none'}}>← Karriere</a>
          </div>
          <h1>{tc('Offene')} <strong>{tc('Stellen.')}</strong></h1>
          <p>{tc('Filtern Sie nach Bereich und Anstellungsart. Klicken Sie auf eine Stelle für Details und das Bewerbungsformular.')}</p>
        </div>
      </section>

      <section className="section section--alt" style={{paddingTop:32}}>
        <div className="container">
          {/* Filter: Bereich */}
          <div style={{marginBottom:20}}>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.16em', textTransform:'uppercase', color:'#777', marginBottom:10}}>{tc('Bereich')}</div>
            <div className="chips">
              <button className={'chip' + (activeType==='all'?' active':'')} onClick={()=>setType('all')}>{tc('Alle')} ({data.jobs.length})</button>
              {types.map(t => (
                <button key={t} className={'chip' + (activeType===t?' active':'')} onClick={()=>setType(t)}>{tc(t)} ({data.jobs.filter(j=>j.type===t).length})</button>
              ))}
            </div>
          </div>
          {/* Filter: Anstellungsart */}
          <div style={{marginBottom:24}}>
            <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.16em', textTransform:'uppercase', color:'#777', marginBottom:10}}>{tc('Anstellungsart')}</div>
            <div className="chips">
              <button className={'chip' + (activeSchedule==='all'?' active':'')} onClick={()=>setSch('all')}>{tc('Alle')}</button>
              {schedules.map(s => (
                <button key={s} className={'chip' + (activeSchedule===s?' active':'')} onClick={()=>setSch(s)}>{tc(s)}</button>
              ))}
            </div>
          </div>

          <div style={{fontSize:13, color:'#777', marginBottom:16}}>{list.length} {tc(list.length===1?'Stelle':'Stellen')} {tc('gefunden')}</div>

          <div style={{display:'flex', flexDirection:'column'}}>
            {list.map((j, i) => (
              <a key={j.id} href={`/${brand}/karriere/stellen/${j.id}`} style={{
                background:'#fff', borderTop: i===0?'1px solid #ececec':'none', borderBottom:'1px solid #ececec',
                padding:'22px 24px', display:'flex', alignItems:'center', gap:24, textDecoration:'none', color:'inherit',
                borderRadius: i===0 ? '8px 8px 0 0' : (i===list.length-1?'0 0 8px 8px':'0')
              }}>
                <div style={{flex:1}}>
                  <div style={{fontSize:17, fontWeight:600, marginBottom:6}}>{j.title}</div>
                  <div style={{display:'flex', gap:16, fontSize:13, color:'#666', flexWrap:'wrap'}}>
                    <span>📍 {j.location}</span><span>⏱ {tc(j.schedule)}</span><span>· {tc(j.type)}</span>
                  </div>
                </div>
                {j.urgent && <span style={{background:'var(--accent)', color:'#fff', fontSize:10, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', padding:'4px 10px', borderRadius:3}}>{tc('Dringend')}</span>}
                <span style={{color:'#999', fontSize:20}}>→</span>
              </a>
            ))}
            {list.length === 0 && (
              <div style={{padding:'40px 24px', textAlign:'center', background:'#fff', borderRadius:8, color:'#777'}}>
                Keine Stellen mit diesem Filter. <button onClick={()=>{setType('all');setSch('all');}} style={{background:'none', border:'none', color:'var(--accent)', cursor:'pointer', fontWeight:600}}>Filter zurücksetzen</button>
              </div>
            )}
          </div>

          {/* Initiativ-Bewerbung Block */}
          <div style={{marginTop:48, padding:'40px 36px', background:'#fff', borderRadius:8, border:'1px dashed #ccc'}}>
            <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:24, flexWrap:'wrap'}}>
              <div style={{flex:'1 1 300px'}}>
                <div style={{fontSize:11, fontWeight:700, letterSpacing:'0.16em', textTransform:'uppercase', color:'var(--accent)', marginBottom:10}}>{tc('Nichts Passendes dabei?')}</div>
                <h3 style={{fontSize:22, fontWeight:600, marginBottom:8}}>{tc('Initiativbewerbung')}</h3>
                <p style={{fontSize:14, color:'#555', lineHeight:1.6, margin:0}}>{tc('Wir freuen uns auch über Bewerbungen ohne konkrete Stellenausschreibung. Erzählen Sie uns, was Sie mitbringen.')}</p>
              </div>
              <button className="btn btn--primary" onClick={()=>{setShowInit(s=>!s); setSubmitted(false);}}>{showInit?tc('Schließen'):tc('Initiativ bewerben')}</button>
            </div>
            {showInit && !submitted && <ApplyForm jobTitle="Initiativbewerbung" onSubmit={()=>setSubmitted(true)} jobsEmail={b.jobsEmail} />}
            {showInit && submitted && <ApplySuccess />}
          </div>
        </div>
      </section>

      {/* Cross-brand hint */}
      <section style={{padding:'0 0 72px'}}>
        <div className="container">
          <div className="xbrand" style={{'--xb': b.switchTo === 'lns' ? '#eb6119' : '#ce171b'}}>
            <div className="xbrand__bar"></div>
            <div className="xbrand__body">
              <div className="xbrand__eyebrow">{tc('Nichts dabei für Sie?')}</div>
              <h2 className="xbrand__title">
                {brand === 'ifm'
                  ? tc('Vielleicht werden Sie bei Quick City LNS fündig — Tiefbau, Glasfaser & Netzausbau.')
                  : tc('Vielleicht werden Sie bei Quick City IFM fündig — Facility Management, GaLaBau & Pflege.')}
              </h2>
            </div>
            <a className="xbrand__btn" href={`/${b.switchTo}/karriere/stellen`}>
              {brand === 'ifm' ? tc('Zu den LNS-Stellen →') : tc('Zu den IFM-Stellen →')}
            </a>
          </div>
        </div>
      </section>

      <style>{`
        .xbrand { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 28px;
          background: #fff; border: 1px solid #ececec; border-radius: 10px; padding: 36px 40px; }
        .xbrand__body { padding-left: 12px; }
        .xbrand__bar { width: 4px; align-self: stretch; background: var(--xb); border-radius: 4px; }
        .xbrand__eyebrow { font-size: 14px; font-weight: 800; letter-spacing: 0.1em; text-transform: uppercase; color: var(--xb); margin-bottom: 12px; }
        .xbrand__title { font-size: clamp(19px, 2vw, 25px); font-weight: 700; line-height: 1.3; letter-spacing: -0.01em; color: #1a1a1a; margin: 0; max-width: 46ch; }
        .xbrand__btn { flex-shrink: 0; display: inline-block; padding: 15px 30px; background: var(--xb); color: #fff;
          font-size: 12px; font-weight: 700; letter-spacing: 0.12em; text-transform: uppercase; text-decoration: none;
          border-radius: 6px; transition: transform 0.2s, filter 0.2s; white-space: nowrap; }
        .xbrand__btn:hover { transform: translateY(-2px); filter: brightness(1.08); }
        @media (max-width: 800px) {
          .xbrand { grid-template-columns: 1fr; gap: 22px; padding: 28px 24px; }
          .xbrand__bar { width: 40px; height: 4px; align-self: start; }
          .xbrand__btn { justify-self: start; }
        }
      `}</style>
    </Layout>
  );
}
// ─────────────────────────────────────────────────────────────────────
function JobDetailPage({ brand, id }) {
  const { lang } = useT();
  const tc = (s) => window.QC_TC ? window.QC_TC(s, lang) : s;
  const data = window.QC_pickCareer ? window.QC_pickCareer(brand, lang) : window.CAREER_DATA[brand];
  const b = window.QC_DATA.brands[brand];
  const job = data.jobs.find(j => j.id === id);
  const [submitted, setSubmitted] = useSC(false);

  useEC(() => { window.scrollTo(0, 0); }, [id]);

  if (!job) {
    return (
      <Layout brand={brand}>
        <section className="hero">
          <div className="container">
            <div className="hero__eyebrow">{tc('Stelle nicht gefunden')}</div>
            <h1>{tc('Diese Stelle gibt es nicht (mehr).')}</h1>
            <p>{tc('Sie wurde möglicherweise bereits besetzt. Schauen Sie sich unsere aktuellen Angebote an.')}</p>
            <div className="hero__ctas">
              <a className="btn btn--primary" href={`/${brand}/karriere/stellen`}>{tc('Alle Stellen ansehen')}</a>
            </div>
          </div>
        </section>
      </Layout>
    );
  }

  // Per-job specific content, with sensible fallbacks
  const role = job.role || [
    `Sie übernehmen Verantwortung in der Position als ${job.title.replace(/ \([^)]+\)/, '')}.`,
    'Sie arbeiten in einem eingespielten Team mit klaren Strukturen und kurzen Wegen.',
    'Je nach Position wirken Sie operativ auf der Baustelle, im Büro oder in der Disposition mit.'
  ];
  const profile = job.profile || [
    'Abgeschlossene Ausbildung oder relevante Berufserfahrung im genannten Bereich (Quereinsteiger willkommen, wo passend).',
    'Selbstständige, zuverlässige Arbeitsweise und Teamgeist.',
    'Gute Deutschkenntnisse für die Verständigung im Team.'
  ];
  const offers = job.offers || data.benefits.map(bn => `${bn.t}: ${bn.d}`);
  const showGenericBenefits = !job.offers; // only show the generic benefit grid if no specific offers given

  return (
    <Layout brand={brand}>
      <section className="hero" style={{paddingBottom:40}}>
        <div className="container">
          <div className="hero__eyebrow">
            <a href={`/${brand}/karriere/stellen`} style={{color:'inherit', textDecoration:'none'}}>← Alle Stellen</a>
          </div>
          <h1 style={{fontSize:'clamp(32px, 4.5vw, 52px)'}}>{job.title}</h1>
          {job.intro && <p style={{fontSize:17, color:'#444', maxWidth:700, marginTop:14, lineHeight:1.55}}>{job.intro}</p>}
          <div style={{display:'flex', gap:20, fontSize:15, color:'#555', flexWrap:'wrap', marginTop:16}}>
            <span>📍 {job.location}</span>
            <span>⏱ {tc(job.schedule)}</span>
            <span>· {tc(job.type)}</span>
            {job.urgent && <span style={{background:'var(--accent)', color:'#fff', fontSize:11, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', padding:'4px 10px', borderRadius:3}}>{tc('Dringend gesucht')}</span>}
          </div>
          <div className="hero__ctas">
            <a className="btn btn--primary" href="#bewerben">{tc('Jetzt bewerben')}</a>
            <a className="btn btn--ghost" href={`mailto:${job.email || b.jobsEmail}?subject=${encodeURIComponent('Bewerbung: ' + job.title)}`}>{tc('Per E-Mail bewerben')}</a>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container" style={{maxWidth:840}}>
          <div style={{display:'grid', gap:40}}>
            <div>
              <div className="section__h">{tc('Deine Rolle bei uns')}</div>
              <h2 style={{fontSize:24, fontWeight:600, marginBottom:18}}>{tc('Was Sie bei uns machen.')}</h2>
              <ul style={{listStyle:'none', padding:0, margin:0}}>
                {role.map((r, i) => <li key={i} style={{padding:'10px 0 10px 28px', position:'relative', fontSize:15, color:'#444', lineHeight:1.6}}>
                  <span style={{position:'absolute', left:0, top:14, width:14, height:2, background:'var(--accent)'}} />{r}
                </li>)}
              </ul>
            </div>

            <div>
              <div className="section__h">{tc('Dein Profil')}</div>
              <h2 style={{fontSize:24, fontWeight:600, marginBottom:18}}>{tc('Was Sie mitbringen.')}</h2>
              <ul style={{listStyle:'none', padding:0, margin:0}}>
                {profile.map((r, i) => <li key={i} style={{padding:'10px 0 10px 28px', position:'relative', fontSize:15, color:'#444', lineHeight:1.6}}>
                  <span style={{position:'absolute', left:0, top:14, width:14, height:2, background:'var(--accent)'}} />{r}
                </li>)}
              </ul>
            </div>

            <div>
              <div className="section__h">{tc('Was wir bieten')}</div>
              <h2 style={{fontSize:24, fontWeight:600, marginBottom:18}}>{tc('Das erwartet Sie.')}</h2>
              {showGenericBenefits ? (
                <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(240px, 1fr))', gap:16}}>
                  {data.benefits.map((bn, i) => (
                    <div key={i} style={{padding:'18px 20px', background:'#fafafa', borderRadius:4}}>
                      <div style={{fontSize:14, fontWeight:600, marginBottom:6, color:'var(--accent)'}}>{bn.t}</div>
                      <div style={{fontSize:13, color:'#555', lineHeight:1.55}}>{bn.d}</div>
                    </div>
                  ))}
                </div>
              ) : (
                <ul style={{listStyle:'none', padding:0, margin:0}}>
                  {offers.map((r, i) => <li key={i} style={{padding:'10px 0 10px 28px', position:'relative', fontSize:15, color:'#444', lineHeight:1.6}}>
                    <span style={{position:'absolute', left:0, top:14, width:14, height:2, background:'var(--accent)'}} />{r}
                  </li>)}
                </ul>
              )}
            </div>
          </div>
        </div>
      </section>

      {/* Apply form */}
      <section id="bewerben" className="section section--alt">
        <div className="container" style={{maxWidth:720}}>
          <div className="section__h">{tc('Jetzt bewerben')}</div>
          <h2 style={{fontSize:28, fontWeight:600, marginBottom:8}}>{tc('Bewerbung für:')} {job.title}</h2>
          <p style={{fontSize:14, color:'#666', marginBottom:32}}>{tc('Wir melden uns innerhalb von 5 Werktagen.')}</p>
          {!submitted
            ? <ApplyForm jobTitle={job.title} onSubmit={()=>setSubmitted(true)} jobsEmail={job.email || b.jobsEmail} />
            : <ApplySuccess />}
        </div>
      </section>
    </Layout>
  );
}

// ─────────────────────────────────────────────────────────────────────
// Apply form + success
// ─────────────────────────────────────────────────────────────────────
function ApplyForm({ jobTitle, onSubmit, jobsEmail }) {
  const [sending, setSending] = useSC(false);
  const [err, setErr] = useSC(false);
  const recipient = jobsEmail === 'tiefbau@quickcity.de' ? 'tiefbau@quickcity.de' : 'info@quickcity.de';

  const submit = async (e) => {
    e.preventDefault();
    if (sending) return;
    const form = e.target;
    if (!form.privacy.checked) return;
    const fd = new FormData(form);
    fd.append('recipient', recipient);
    fd.append('jobTitle', jobTitle || '');
    setSending(true); setErr(false);
    try {
      const res = await fetch('bewerbung.php', { method: 'POST', body: fd });
      const data = await res.json().catch(() => ({ ok: false }));
      if (res.ok && data.ok) { onSubmit(); }
      else { setErr(true); }
    } catch (e2) { setErr(true); }
    finally { setSending(false); }
  };

  return (
    <form className="career-form" onSubmit={submit} style={{background:'#fff', padding:'32px 32px 28px', borderRadius:8, marginTop:20, border:'1px solid #ececec'}}>
      <input type="text" name="website" tabIndex="-1" autoComplete="off" style={{position:'absolute',left:'-9999px',width:1,height:1,opacity:0}} aria-hidden="true" />
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:0}}>
        <CField label="Vorname *" name="firstname" required />
        <CField label="Nachname *" name="lastname" required />
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
        <CField label="E-Mail *" name="email" type="email" required />
        <CField label="Telefon *" name="phone" type="tel" required />
      </div>
      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:14}}>
        <CField label="Frühestmöglicher Eintritt" name="start" type="date" />
        <CField label="Gehaltsvorstellung" name="salary" />
      </div>
      <CField label="Nachricht / Motivation" name="message" textarea />

      <div style={{marginTop:8, marginBottom:18, padding:'18px 20px', background:'#fafafa', border:'1px solid #ececec', borderRadius:6}}>
        <div style={{fontSize:13, fontWeight:700, color:'#1a1a1a', marginBottom:4}}>Vollständige Bewerbungsunterlagen *</div>
        <div style={{fontSize:13, color:'#666', lineHeight:1.6, marginBottom:16}}>
          Bitte laden Sie Ihre vollständigen Unterlagen hoch: <strong>Anschreiben</strong>, <strong>Lebenslauf</strong> sowie <strong>relevante Zeugnisse &amp; Nachweise</strong> (Arbeits-, Ausbildungs- und ggf. Qualifikationszeugnisse).
        </div>
        <CField label="Anschreiben *" name="cover" type="file" required accept=".pdf,.doc,.docx" hint="PDF oder Word, max. 10 MB" />
        <CField label="Lebenslauf *" name="cv" type="file" required accept=".pdf,.doc,.docx" hint="PDF oder Word, max. 10 MB" />
        <CField label="Zeugnisse & Nachweise" name="certificates" type="file" multiple accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" hint="Mehrfachauswahl möglich · PDF, Word oder Bild, je max. 10 MB" />
        <div style={{marginBottom:0}}>
          <CField label="Sonstige Dokumente (optional)" name="other" type="file" multiple accept=".pdf,.doc,.docx,.jpg,.jpeg,.png" hint="z. B. Führerschein, Zertifikate, Portfolio" />
        </div>
      </div>

      <label style={{display:'flex', gap:10, alignItems:'flex-start', fontSize:12.5, color:'#555', lineHeight:1.5, marginBottom:4, cursor:'pointer'}}>
        <input type="checkbox" name="privacy" required style={{marginTop:3, flexShrink:0}} />
        <span>Ich habe die <a href="/lns/datenschutz" style={{color:'var(--accent)'}}>Datenschutzerklärung</a> gelesen und stimme der Verarbeitung meiner Bewerbungsdaten zu. *</span>
      </label>

      <div style={{display:'flex', gap:14, alignItems:'center', marginTop:16, paddingTop:18, borderTop:'1px solid #eee', flexWrap:'wrap'}}>
        <button type="submit" className="btn btn--primary" disabled={sending}>{sending ? 'Wird gesendet …' : 'Bewerbung senden'}</button>
        <a href={`mailto:${jobsEmail}?subject=${encodeURIComponent('Bewerbung: ' + jobTitle)}`} style={{color:'var(--accent)', fontWeight:500, fontSize:13}}>oder per E-Mail an {jobsEmail}</a>
      </div>
      {err && <div style={{fontSize:12.5, color:'var(--accent)', fontWeight:600, marginTop:12}}>Senden fehlgeschlagen. Bitte prüfen Sie die Dateigrößen (max. 22 MB gesamt) oder bewerben Sie sich per E-Mail.</div>}
      <div style={{fontSize:11, color:'#999', marginTop:14, lineHeight:1.5}}>* Pflichtfeld. Unvollständige Bewerbungen können wir leider nicht berücksichtigen.</div>
    </form>
  );
}

function ApplySuccess() {
  return (
    <div style={{padding:'40px 24px', textAlign:'center', background:'#fff', borderRadius:8, marginTop:20, border:'1px solid #ececec'}}>
      <div style={{width:64, height:64, borderRadius:'50%', background:'var(--accent)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:32, margin:'0 auto 18px'}}>✓</div>
      <h3 style={{fontSize:24, fontWeight:600, marginBottom:10}}>Vielen Dank!</h3>
      <p style={{fontSize:15, color:'#555', lineHeight:1.6, maxWidth:440, margin:'0 auto'}}>Ihre Bewerbung ist eingegangen. Eine Bestätigung haben wir Ihnen per E-Mail geschickt — bitte prüfen Sie ggf. auch Ihren <strong>Spam-Ordner</strong>. Wir melden uns so bald wie möglich bei Ihnen.</p>
    </div>
  );
}

Object.assign(window, { CareerLanding, JobsPage, JobDetailPage });
