// Engcelerate — single page app component
const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────────────
// Reusable bits
// ─────────────────────────────────────────────────────────────
function Portrait({ w, h, caption }) {
  return (
    <div className="portrait" style={{ width: w, height: h }}>
      <svg width="100%" height="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
        <defs>
          <pattern id={`p${w}`} width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
            <line x1="0" y1="0" x2="0" y2="6" stroke="#1a2742" strokeWidth="0.6" opacity="0.18"/>
          </pattern>
        </defs>
        <rect width={w} height={h} fill={`url(#p${w})`}/>
      </svg>
      <div className="portrait-cap">{caption}</div>
    </div>
  );
}

function FaqList({ items }) {
  const [open, setOpen] = useState(0);
  return (
    <div className="faq">
      {items.map((f, i) => (
        <div key={i} className={`faq-item ${open===i?'open':''}`}>
          <button className="faq-q" onClick={() => setOpen(open===i ? -1 : i)}>
            <span>{f.q}</span>
            <span className="faq-plus">{open===i ? '−' : '+'}</span>
          </button>
          {open===i && <div className="faq-a">{f.a}</div>}
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Price calculator — uses shared/data.js calcPrice()
// ─────────────────────────────────────────────────────────────
function PriceCalculator({ lang = 'en', onRegister }) {
  const [paymentType, setPaymentType] = useState('monthly');
  const [frequency, setFrequency]     = useState('1/week');
  const [pkgSize, setPkgSize]         = useState('10');
  const [dayTime, setDayTime]         = useState('weekday-day');
  const [invoice, setInvoice]         = useState('private');
  const [groupSize, setGroupSize]     = useState(1);
  const [referrals, setReferrals]     = useState(0);
  const [location, setLocation]       = useState('online'); // 'online' | 'offsite'

  const result = window.calcPrice({
    paymentType, frequency, pkgSize, dayTime, invoice, groupSize, referrals,
  });

  const L = lang === 'pl'
    ? {
        title: 'Kalkulator cen', sub: 'Na podstawie cennika',
        payType: 'Sposób', monthly: 'Plan miesięczny', pkg: 'Pakiet',
        freq: 'Częstotliwość', pkgSize: 'Wielkość pakietu', lessons: 'lekcji',
        dayTime: 'Dzień / godzina', weekdayDay: 'Pn–Pt · 8–16',
        weekdayEve: 'Pn–Pt · 16–22', weekend: 'Sb–Nd',
        invoice: 'Faktura', private: 'Prywatna', business: 'Firmowa',
        students: 'Uczniów', solo: 'indywidualnie', group2: 'grupa',
        groupHint: 'każdy płaci 60% pełnej ceny',
        refs: 'Polecenia', refsHint: '−5 PLN za każde, łącznie max −20',
        perLesson: 'za lekcję', perStudent: 'na ucznia', groupTotalLbl: 'łącznie za grupę',
        perMonth: 'miesięcznie', forPkg: 'za pakiet',
        breakdown: 'Kalkulacja', register: 'Zarezerwuj darmową lekcję',
        premium: 'Godziny premium — rezerwowane tylko po akceptacji dopłaty.',
        location: 'Lokalizacja', locOnline: 'Online lub u mnie', locOffsite: 'Z dojazdem',
        offsiteTitle: 'Wycena indywidualna',
        offsiteBody: 'Online lub u mnie — ta sama stawka. Jeśli mam dojechać do Ciebie, dopłata zależy od odległości i czasu dojazdu. Zarezerwuj darmową lekcję próbną i podaj adres, a wrócę z konkretną kwotą.',
        offsiteCta: 'Poprosić o wycenę',
        rBase: 'Stawka bazowa', rEvening: 'Wieczór (Pn–Pt 16–22)', rWeekend: 'Weekend', rBusiness: 'Faktura firmowa',
        rPerLesson: 'Cena za lekcję', rLessons: 'Liczba lekcji', rSubtotal: 'Suma częściowa',
        rGroup: 'Grupa', rGroupNote: 'każdy płaci 60%',
        rPerStudent: 'Na ucznia', rGroupTotal: 'Łącznie za grupę',
        rRefs: 'Polecenia', rTotal: 'Do zapłaty',
      }
    : {
        title: 'Price calculator', sub: 'Live from the pricing sheet',
        payType: 'Payment', monthly: 'Monthly plan', pkg: 'Lesson package',
        freq: 'Frequency', pkgSize: 'Package size', lessons: 'lessons',
        dayTime: 'Day / time', weekdayDay: 'Mon–Fri · 8–16',
        weekdayEve: 'Mon–Fri · 16–22', weekend: 'Sat–Sun',
        invoice: 'Invoice', private: 'Private', business: 'Business',
        students: 'Students', solo: 'individual', group2: 'group',
        groupHint: 'each pays 60% of full price',
        refs: 'Referrals', refsHint: '−5 PLN each, flat cap −20 off total',
        perLesson: 'per lesson', perStudent: 'per student', groupTotalLbl: 'group total',
        perMonth: 'per month', forPkg: 'for the package',
        breakdown: 'Breakdown', register: 'Book free trial',
        premium: 'Premium hours — booked only when the surcharge is accepted.',
        location: 'Location', locOnline: 'Online or at my place', locOffsite: 'I travel to you',
        offsiteTitle: 'Quoted on request',
        offsiteBody: 'Online or at my place — same rate. If I travel to you, a surcharge applies based on distance and travel time. Book the free trial and share the address — I’ll come back with an exact figure.',
        offsiteCta: 'Request a quote',
        rBase: 'Base rate', rEvening: 'Evening (Mon–Fri 16–22)', rWeekend: 'Weekend', rBusiness: 'Business invoice',
        rPerLesson: 'Price per lesson', rLessons: 'Lessons', rSubtotal: 'Subtotal',
        rGroup: 'Group', rGroupNote: 'each pays 60%',
        rPerStudent: 'Per student', rGroupTotal: 'Group total',
        rRefs: 'Referrals', rTotal: 'You pay',
      };
  const totalLabel = paymentType === 'monthly' ? L.perMonth : L.forPkg;

  return (
    <div className="calc">
      <div className="calc-head">
        <div className="calc-title">{L.title}</div>
        <div className="calc-sub">{L.sub}</div>
      </div>

      <div className="calc-grid">
        <div className="calc-field">
          <label>{L.payType}</label>
          <div className="pill-row">
            <button className={`pill ${paymentType==='monthly'?'on':''}`} onClick={() => setPaymentType('monthly')}>{L.monthly}</button>
            <button className={`pill ${paymentType==='package'?'on':''}`} onClick={() => setPaymentType('package')}>{L.pkg}</button>
          </div>
        </div>

        {paymentType === 'monthly' ? (
          <div className="calc-field">
            <label>{L.freq}</label>
            <div className="pill-row">
              {['1/week','2/week','3/week'].map(f => (
                <button key={f} className={`pill ${frequency===f?'on':''}`} onClick={() => setFrequency(f)}>{f}</button>
              ))}
            </div>
          </div>
        ) : (
          <div className="calc-field">
            <label>{L.pkgSize}</label>
            <div className="pill-row">
              {['1','5','10','20'].map(s => (
                <button key={s} className={`pill ${pkgSize===s?'on':''}`} onClick={() => setPkgSize(s)}>{s} {L.lessons}</button>
              ))}
            </div>
          </div>
        )}

        <div className="calc-field" style={{ gridColumn: '1 / -1' }}>
          <label>{L.dayTime}</label>
          <div className="pill-row">
            <button className={`pill ${dayTime==='weekday-day'?'on':''}`} onClick={() => setDayTime('weekday-day')}>{L.weekdayDay}</button>
            <button className={`pill ${dayTime==='weekday-evening'?'on':''}`} onClick={() => setDayTime('weekday-evening')}>{L.weekdayEve} <em>+100</em></button>
            <button className={`pill ${dayTime==='weekend'?'on':''}`} onClick={() => setDayTime('weekend')}>{L.weekend} <em>+200</em></button>
          </div>
        </div>

        <div className="calc-field">
          <label>{L.invoice}</label>
          <div className="pill-row">
            <button className={`pill ${invoice==='private'?'on':''}`} onClick={() => setInvoice('private')}>{L.private}</button>
            <button className={`pill ${invoice==='business'?'on':''}`} onClick={() => setInvoice('business')}>{L.business} <em>+50</em></button>
          </div>
        </div>

        <div className="calc-field" style={{ gridColumn: '1 / -1' }}>
          <label>{L.location}</label>
          <div className="pill-row">
            <button className={`pill ${location==='online'?'on':''}`} onClick={() => setLocation('online')}>{L.locOnline}</button>
            <button className={`pill ${location==='offsite'?'on':''}`} onClick={() => setLocation('offsite')}>{L.locOffsite} <em>{lang==='pl'?'wycena':'quote'}</em></button>
          </div>
        </div>

        <div className="calc-field">
          <label>{L.students}</label>
          <div className="step">
            <button onClick={() => setGroupSize(Math.max(1, groupSize-1))}>−</button>
            <span>{groupSize} {groupSize===1 ? L.solo : L.group2}</span>
            <button onClick={() => setGroupSize(Math.min(6, groupSize+1))}>+</button>
          </div>
        </div>

        <div className="calc-field" style={{ gridColumn: '1 / -1' }}>
          <label>{L.refs} <span style={{textTransform:'none',letterSpacing:0,opacity:.7,fontWeight:400,marginLeft:6,fontFamily:'inherit'}}>({L.refsHint})</span></label>
          <div className="step">
            <button onClick={() => setReferrals(Math.max(0, referrals-1))}>−</button>
            <span>{referrals}</span>
            <button onClick={() => setReferrals(Math.min(4, referrals+1))}>+</button>
          </div>
        </div>
      </div>

      {location === 'offsite' ? (
        <div className="calc-result calc-quote">
          <div>
            <div className="calc-big">
              <span className="calc-num" style={{fontSize:'64px'}}>{lang==='pl'?'Wycena':'Quote'}</span>
            </div>
            <div className="calc-caption">{L.offsiteTitle}</div>
          </div>
          <div>
            <p style={{margin:'0 0 12px',fontSize:'14px',lineHeight:1.55,color:'var(--ink)'}}>{L.offsiteBody}</p>
            <div className="calc-breakdown-title">{lang==='pl'?'Stawka bazowa (online)':'Online baseline'}</div>
            <div className="calc-breakdown-row">
              <span>{lang==='pl'?'Przed dop\u0142at\u0105 za dojazd':'Before travel surcharge'}</span>
              <span>{result.perLesson} PLN / {L.perLesson.replace('per ','')}</span>
            </div>
          </div>
        </div>
      ) : (
      <div className="calc-result calc-receipt">
        {/* Big headline */}
        <div className="calc-total">
          <div className="calc-total-label">{L.rTotal} · {totalLabel}</div>
          <div className="calc-total-value">
            <span className="calc-num">{result.total}</span>
            <span className="calc-unit">PLN</span>
          </div>
          {result.isGroup && (
            <div className="calc-total-sub">
              {result.perStudentTotal} PLN {L.rPerStudent.toLowerCase()} · {result.groupSize} {L.rPerStudent.toLowerCase().replace('per ','')}
            </div>
          )}
        </div>

        {/* Plain-English one-liner */}
        <div className="calc-summary">
          {result.lessonsCount} {L.rLessons.toLowerCase()} × {result.perLesson} PLN
          {result.isGroup && ` ${L.rPerStudent.toLowerCase()}`}
        </div>

        {/* Itemised list — only surcharges & discounts */}
        {(result.surcharges.length > 0 || result.isGroup || result.refDiscount > 0) && (
          <ul className="calc-items">
            <li><span>{L.rBase}</span><span>{result.basePerLesson} PLN</span></li>
            {result.surcharges.map(s => (
              <li key={s.key} className="add">
                <span>{s.key==='evening'?L.rEvening:s.key==='weekend'?L.rWeekend:L.rBusiness}</span>
                <span>+{s.amount} PLN</span>
              </li>
            ))}
            {result.isGroup && (
              <li className="sub">
                <span>{L.rGroup} · {L.rGroupNote}</span>
                <span>× 0.60</span>
              </li>
            )}
            {result.refDiscount > 0 && (
              <li className="discount">
                <span>{L.rRefs} × {result.refs}</span>
                <span>−{result.refDiscount} PLN</span>
              </li>
            )}
          </ul>
        )}

        {result.premium && <div className="calc-premium">⚠ {L.premium}</div>}
      </div>
      )}

      <button className="calc-cta" onClick={() => onRegister && onRegister({
        paymentType, frequency, pkgSize, dayTime, invoice, groupSize, referrals, location,
        perLesson: result.perLesson, total: result.total,
        mode: location === 'offsite' ? 'inperson' : 'online',
      })}>{location==='offsite' ? L.offsiteCta : L.register} →</button>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Registration — 2-step
// ─────────────────────────────────────────────────────────────
function RegistrationForm({ lang = 'en', prefill = {}, onClose, onOpenTerms }) {
  const P = window.ENG_DATA.pricing;
  const [step, setStep] = useState(1);
  const [f, setF] = useState({
    startWith: '',
    name: '', email: '', phone: '', guardian: '',

    mode: 'online', notes: '', preferred: '', startDate: '', consent: false,
    ...prefill,
  });
  const set = (k) => (e) => setF({ ...f, [k]: e?.target ? (e.target.type==='checkbox'?e.target.checked:e.target.value) : e });
  const L = lang === 'pl' ? REG_PL : REG_EN;
  const canSubmit = f.name && f.email && f.consent;
  const [status, setStatus] = useState('idle');

  async function handleSubmit() {
    const url = window.ENG_DATA.contact.webAppUrl;
    if (!url) { setStep(3); return; }
    setStatus('sending');
    try {
      const fd = new FormData();
      const fields = {
        ts: new Date().toLocaleString('sv-SE', { timeZone: 'Europe/Warsaw' }), lang,
        startWith: f.startWith, name: f.name, email: f.email,
        phone: f.phone, guardian: f.guardian, mode: f.mode,
        preferred: f.preferred, startDate: f.startDate, notes: f.notes,
        consent: 'Yes',
        paymentType: prefill.paymentType || '',
        frequency: prefill.paymentType === 'monthly' ? (prefill.frequency || '') : '',
        pkgSize: prefill.paymentType === 'package' ? (prefill.pkgSize || '') : '',
        dayTime: prefill.dayTime || '',
        invoice: prefill.invoice || '', groupSize: prefill.groupSize || '',
        referrals: prefill.referrals || '', perLesson: prefill.perLesson || '',
        total: prefill.total || '', location: prefill.location || '',
      };
      Object.entries(fields).forEach(([k, v]) => fd.append(k, String(v)));
      await fetch(url, { method: 'POST', mode: 'no-cors', body: fd });
      setStep(3);
    } catch {
      setStatus('error');
    }
  }

  const dtLabel = {
    'weekday-day': lang === 'pl' ? 'Pn–Pt · 8–16' : 'Mon–Fri · 8–4pm',
    'weekday-evening': lang === 'pl' ? 'Wieczory' : 'Evenings',
    'weekend': lang === 'pl' ? 'Weekend' : 'Weekends',
  }[prefill.dayTime];
  const planSummary = prefill.perLesson ? {
    plan: prefill.paymentType === 'monthly'
      ? `${prefill.frequency} · ${dtLabel}`
      : `${prefill.pkgSize} ${lang === 'pl' ? 'lekcji' : 'lessons'} · ${dtLabel}`,
    invoice: prefill.invoice === 'business' ? L.planBusiness : L.planPrivate,
    offsite: prefill.location === 'offsite',
  } : null;

  if (step === 3) {
    return (
      <div className="reg reg-done">
        <div className="reg-success">
          <div className="reg-check">✓</div>
          <h3>{L.thanks}</h3>
          <p>{L.thanksBody}</p>
          <button className="btn btn-primary" onClick={onClose}>{L.close}</button>
        </div>
      </div>
    );
  }
  return (
    <div className="reg">
      {planSummary && (
        <div className="reg-plan">
          <div className="reg-plan-header">{L.yourPlan}</div>
          {planSummary.offsite ? (
            <div className="reg-plan-row">{L.planTravel}</div>
          ) : (
            <>
              <div className="reg-plan-row">
                <span>{planSummary.plan}</span>
                <span>{planSummary.invoice}</span>
              </div>
              {prefill.groupSize > 1 && <div className="reg-plan-row"><span>{prefill.groupSize} {L.planStudents}</span></div>}
              {prefill.referrals > 0 && <div className="reg-plan-row"><span>−{prefill.referrals * 5} PLN {L.planDiscount}</span></div>}
              <div className="reg-plan-price">
                <strong>{prefill.perLesson} PLN</strong> / {L.planPerLesson}
                {' · '}
                <strong>{prefill.total} PLN</strong> {prefill.paymentType === 'monthly' ? L.planPerMonth : L.planForPkg}
              </div>
            </>
          )}
          <div className="reg-plan-note">{L.planNote}</div>
        </div>
      )}
      <div className="reg-head">
        <div>
          <div className="reg-step">{lang==='pl'?'Krok':'Step'} {step} / 2</div>
          <h3>{step===1 ? L.yourDetails : L.lessonDetails}</h3>
        </div>
        {onClose && <button className="reg-x" onClick={onClose}>×</button>}
      </div>
      {step === 1 && (
        <div className="reg-grid">
          <Field label={L.startWith} required full>
            <div className="pill-row">
              {['trial30','trial60','ongoing'].map(s => (
                <button key={s} className={`pill ${f.startWith===s?'on':''}`} onClick={() => setF({...f, startWith:s})}>{L['start_'+s]}</button>
              ))}
            </div>
          </Field>
          <Field label={L.name} required><input value={f.name} onChange={set('name')} placeholder="Jan Kowalski"/></Field>
          <Field label={L.email} required><input type="email" value={f.email} onChange={set('email')} placeholder="jan@example.com"/></Field>
          <Field label={L.phone}><input type="tel" value={f.phone} onChange={set('phone')} placeholder="+48 …"/></Field>
          <Field label={L.guardian}><input value={f.guardian} onChange={set('guardian')} placeholder={L.guardianPh}/></Field>
        </div>
      )}
      {step === 2 && (
        <div className="reg-grid">
          <Field label={L.mode} full>
            <div className="pill-row">
              {['online','apartment','local','travel'].map(m => (
                <button key={m} className={`pill ${f.mode===m?'on':''}`} onClick={() => setF({...f,mode:m})}>{L['mode_'+m]}</button>
              ))}
            </div>
          </Field>
          <Field label={L.preferred} full><input value={f.preferred} onChange={set('preferred')} placeholder={L.preferredPh}/></Field>
          <Field label={L.startDate} full><input value={f.startDate} onChange={set('startDate')} placeholder={L.startDatePh}/></Field>

          <Field label={L.notes} full><textarea rows="3" value={f.notes} onChange={set('notes')} placeholder={L.notesPh}/></Field>
          <Field full>
            <label className="check">
              <input type="checkbox" checked={f.consent} onChange={set('consent')}/>
              <span>
                {L.consentPre}{' '}
                <a className="inline-link" onClick={(e) => { e.preventDefault(); onOpenTerms && onOpenTerms(); }}>{L.consentTerms}</a>
                {L.consentPost}
              </span>
            </label>
          </Field>
        </div>
      )}
      <div className="reg-actions">
        {step > 1 && <button className="reg-ghost" onClick={() => setStep(step-1)}>← {L.back}</button>}
        <div style={{flex:1}}/>
        {step === 1 && <button className="btn btn-primary" onClick={() => setStep(2)} disabled={!f.startWith || !f.name || !f.email}>{L.next} →</button>}
        {step === 2 && <button className="btn btn-primary" disabled={!canSubmit || status === 'sending'} onClick={handleSubmit}>{status === 'sending' ? L.sending : L.submit}</button>}
      </div>
      {status === 'error' && (
        <div className="reg-error">
          {L.sendError}{' '}
          <a href={`mailto:${window.ENG_DATA.contact.email}`} className="inline-link">{L.sendErrorLink}</a>
        </div>
      )}
    </div>
  );
}

function Field({ label, required, full, children }) {
  return (
    <div className={`field ${full?'field-full':''}`}>
      {label && <label>{label}{required && <span className="req">*</span>}</label>}
      {children}
    </div>
  );
}

const REG_EN = {
  yourDetails: 'About you', lessonDetails: 'When & what',
  name: 'Full name', email: 'Email', phone: 'Phone',
  guardian: 'Parent / guardian name', guardianPh: 'If the student is under 18',
  startWith: 'Start with',
  start_trial30: '30-min trial (free)',
  start_trial60: '60-min trial (100 PLN)',
  start_ongoing: 'Ongoing plan',
  preferred: 'Available days & times',
  preferredPh: 'e.g. Mon 14:00 & 16:00, Tue 09:00–13:00, Sat mornings',
  startDate: 'Preferred start date',
  startDatePh: 'e.g. 05.07 or asap',
  mode: 'Lesson location',
  mode_online: 'Online',
  mode_apartment: "Tutor's apartment",
  mode_local: "Tutor's local area",
  mode_travel: 'Travel to me (fee TBD)',
  notes: 'About you & goals',
  notesPh: 'Where you live, native language, profession, what you want to improve…',
  consent: 'I agree to be contacted about my free trial and accept the terms.',
  consentPre: 'I agree to be contacted about my free trial and accept the',
  consentTerms: 'terms & conditions',
  consentPost: '.',
  back: 'Back', next: 'Next', submit: 'Send registration',
  thanks: 'You’re in — nice!', thanksBody: 'Check your inbox shortly. Andrew will be in touch to lock in a time that suits you.',
  close: 'Close',
  yourPlan: 'Your plan',
  planBusiness: 'Business invoice', planPrivate: 'Private invoice',
  planStudents: 'students', planDiscount: 'referral discount',
  planPerLesson: 'lesson', planPerMonth: '/ month', planForPkg: 'for pack',
  planTravel: 'Travel to you — rate to be quoted',
  planNote: 'No commitment — just your preferences so we can prepare.',
  sending: 'Sending…',
  sendError: 'Something went wrong.', sendErrorLink: 'Email me directly',
};
const REG_PL = {
  yourDetails: 'O Tobie', lessonDetails: 'Kiedy i co',
  name: 'Imię i nazwisko', email: 'E-mail', phone: 'Telefon',
  guardian: 'Rodzic / opiekun', guardianPh: 'Jeśli uczeń jest niepełnoletni',
  startWith: 'Zacznij od',
  start_trial30: 'Lekcja próbna 30 min (gratis)',
  start_trial60: 'Lekcja próbna 60 min (100 PLN)',
  start_ongoing: 'Stały plan',
  preferred: 'Dostępne dni i godziny',
  preferredPh: 'np. pn. 14:00 i 16:00, wt. 09:00–13:00, sob. rano',
  startDate: 'Preferowana data rozpoczęcia',
  startDatePh: 'np. 05.07 lub jak najszybciej',
  mode: 'Miejsce lekcji',
  mode_online: 'Online',
  mode_apartment: 'U lektora',
  mode_local: 'Okolica lektora',
  mode_travel: 'Z dojazdem (opłata do ustalenia)',
  notes: 'O Tobie i cele',
  notesPh: 'Gdzie mieszkasz, język ojczysty, zawód, co chcesz poprawić…',
  consent: 'Zgadzam się na kontakt w sprawie darmowej lekcji i akceptuję regulamin.',
  consentPre: 'Zgadzam się na kontakt w sprawie darmowej lekcji i akceptuję',
  consentTerms: 'regulamin',
  consentPost: '.',
  back: 'Wstecz', next: 'Dalej', submit: 'Wyślij',
  thanks: 'Gotowe!', thanksBody: 'Sprawdź skrzynkę. Andrew skontaktuje się z Tobą, aby ustalić dogodny termin.',
  close: 'Zamknij',
  yourPlan: 'Twój plan',
  planBusiness: 'Faktura firmowa', planPrivate: 'Faktura prywatna',
  planStudents: 'uczestników', planDiscount: 'zniżka za polecenie',
  planPerLesson: 'lekcję', planPerMonth: '/ mies.', planForPkg: 'za pakiet',
  planTravel: 'Dojazd do Ciebie — cena do wyceny',
  planNote: 'To dopiero Twoje preferencje — wszystko potwierdzamy przed pierwszą lekcją.',
  sending: 'Wysyłanie…',
  sendError: 'Coś poszło nie tak.', sendErrorLink: 'Napisz bezpośrednio',
};

// ─────────────────────────────────────────────────────────────
// Chatbot
// ─────────────────────────────────────────────────────────────
function Chatbot({ lang = 'en', onRegister }) {
  const [open, setOpen] = useState(false);
  const [msgs, setMsgs] = useState([
    { role: 'assistant', content: lang==='pl'
      ? 'Cześć! Jestem asystentem Engcelerate. Mogę pomóc z cennikiem, dostępnością, albo umówić darmową lekcję. O co chcesz zapytać?'
      : 'Hi! I’m Engcelerate’s assistant. I can help with pricing, availability, or book your free trial. What would you like to know?' },
  ]);
  const [input, setInput] = useState('');
  const [busy, setBusy] = useState(false);
  const endRef = useRef(null);
  useEffect(() => { endRef.current?.scrollTo(0, 99999); }, [msgs, open]);
  const quick = lang==='pl'
    ? ['Ile kosztuje lekcja?','Jak działa darmowa lekcja?','Czy uczysz online?','Umów mnie']
    : ['How much is a lesson?','How does the free trial work?','Do you teach online?','Book me in'];
  const send = async (text) => {
    const t = (text ?? input).trim();
    if (!t || busy) return;
    setInput('');
    const next = [...msgs, { role: 'user', content: t }];
    setMsgs(next); setBusy(true);
    try {
      const system = `You are the friendly assistant for Engcelerate, English tutoring run by Andrew (Australian, in Poznań). Reply in ${lang==='pl'?'Polish':'English'}, 2-4 sentences. Facts:
- Free 30-min trial; paid 60-min trial 100 PLN.
- Monthly Plan daytime (weekday 8-16, private, individual): 1/week 150, 2/week 140, 3/week 130 PLN per lesson.
- Lesson Package daytime: 1=200, 5=190, 10=180, 20=170 PLN/lesson.
- Weekday evening (16-22) +100 PLN; weekend (Sat-Sun) +200 PLN; business invoice +50 PLN.
- Group: each student pays 60% of full per-lesson price.
- Referrals: -5 PLN each, flat cap -20 off total.
- Levels A1 to C2; adults, children, groups.
- Hours Mon-Sun 08:00-22:00. Online or in-person (Poznań).
If user wants to book, end with [REGISTER] on its own line.`;
      const reply = await window.claude.complete({
        messages: next.map(m => ({ role: m.role, content: m.content })),
        system,
      });
      const register = /\[REGISTER\]/.test(reply);
      const clean = reply.replace(/\[REGISTER\]/g,'').trim();
      setMsgs([...next, { role: 'assistant', content: clean, register }]);
    } catch (e) {
      setMsgs([...next, { role: 'assistant', content: lang==='pl'?'Przepraszam — coś poszło nie tak.':'Sorry — something went wrong.' }]);
    } finally { setBusy(false); }
  };
  if (!open) {
    return (
      <button className="chat-fab" onClick={() => setOpen(true)}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
        <span>{lang==='pl'?'Zapytaj':'Ask Andrew’s bot'}</span>
      </button>
    );
  }
  return (
    <div className="chat chat-float">
      <div className="chat-head">
        <div className="chat-dot"/>
        <div>
          <b>{lang==='pl'?'Asystent Engcelerate':'Engcelerate assistant'}</b>
          <div className="chat-sub">{lang==='pl'?'Zwykle odpowiada w kilka sekund':'Usually replies in a few seconds'}</div>
        </div>
        <button className="chat-x" onClick={() => setOpen(false)}>×</button>
      </div>
      <div className="chat-body" ref={endRef}>
        {msgs.map((m, i) => (
          <div key={i} className={`chat-msg chat-${m.role}`}>
            <div className="chat-bubble">
              {m.content}
              {m.register && (
                <button className="chat-inline-cta" onClick={() => onRegister && onRegister()}>
                  {lang==='pl'?'Otwórz formularz →':'Open registration →'}
                </button>
              )}
            </div>
          </div>
        ))}
        {busy && <div className="chat-msg chat-assistant"><div className="chat-bubble chat-typing"><span/><span/><span/></div></div>}
      </div>
      <div className="chat-quick">
        {quick.map(q => <button key={q} onClick={() => send(q)}>{q}</button>)}
      </div>
      <div className="chat-input">
        <input value={input} onChange={e=>setInput(e.target.value)}
          onKeyDown={e => e.key==='Enter' && send()} placeholder={lang==='pl'?'Napisz wiadomość…':'Type a message…'}/>
        <button onClick={() => send()} disabled={busy || !input.trim()}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
        </button>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Legal modal — Terms & Privacy
// ─────────────────────────────────────────────────────────────
function LegalModal({ lang = 'en', doc = 'terms', onClose }) {
  const L = lang === 'pl' ? LEGAL_PL : LEGAL_EN;
  const d = L[doc];
  return (
    <div className="legal">
      <div className="legal-head">
        <div>
          <div className="legal-eyebrow">— {d.eyebrow}</div>
          <h3>{d.title}</h3>
          <div className="legal-updated">{L.updated}: {L.updatedDate}</div>
        </div>
        <button className="reg-x" onClick={onClose} aria-label="Close">×</button>
      </div>

      <div className="legal-body">
        <p className="legal-lede">{d.lede}</p>

        {doc === 'terms' && (
          <>
            <ol className="legal-list">
              {L.terms.items.map((it, i) => (
                <li key={i}>
                  <span className="legal-num">{String(i+1).padStart(2,'0')}</span>
                  <div>
                    <b>{it.t}</b>
                    <p>{it.d}</p>
                  </div>
                </li>
              ))}
            </ol>

            <div className="legal-subhead">{L.terms.packageTitle}</div>
            <p className="legal-sub">{L.terms.packageLede}</p>
            <table className="legal-table">
              <thead>
                <tr>
                  <th>{L.terms.pkgLessons}</th>
                  <th>{L.terms.pkgExpiry}</th>
                </tr>
              </thead>
              <tbody>
                {[[1,30],[5,45],[10,90],[20,180]].map(([n, d]) => (
                  <tr key={n}><td>{n} {L.terms.pkgLessonWord}</td><td>{d} {L.terms.pkgDaysWord}</td></tr>
                ))}
              </tbody>
            </table>
          </>
        )}

        {doc === 'privacy' && (
          <>
            {L.privacy.sections.map((s, i) => (
              <div key={i} className="legal-section">
                <b>{s.t}</b>
                <p>{s.d}</p>
              </div>
            ))}
            <p className="legal-draft">{L.privacy.draftNote}</p>
          </>
        )}
      </div>

      <div className="legal-foot">
        <a href={`mailto:${(window.ENG_DATA?.contact?.email) || 'hello@engcelerate.com'}`}>
          {L.questions}
        </a>
        <button className="btn btn-primary" onClick={onClose}>{L.close}</button>
      </div>
    </div>
  );
}

const LEGAL_EN = {
  updated: 'Last updated',
  updatedDate: '22 April 2026',
  questions: 'Questions? Email me →',
  close: 'Close',
  terms: {
    eyebrow: 'Terms & conditions',
    title: 'Terms & conditions',
    lede: 'These terms exist from previous experience — to encourage respect for, and security of, the valuable time of the tutor and all learners.',
    items: [
      { t: 'Payment in advance',
        d: 'Payments are due in advance, in PLN.' },
      { t: 'Monthly billing',
        d: 'Monthly payments must be paid by the 1st of every month, or on a previously agreed day (for example, the 10th).' },
      { t: 'Lesson expiry',
        d: 'Monthly lessons expire at month end. Lesson packages expire according to the schedule below.' },
      { t: '24-hour cancellation notice',
        d: 'Cancellations and rescheduling require at least 24 hours advance notice.' },
      { t: 'Missed lessons',
        d: 'Missed lessons are forfeited.' },
      { t: 'Punctuality',
        d: 'Lessons must start and finish on time. If the student is late, that time is lost with no price reduction.' },
      { t: 'Local area lessons',
        d: "Local area lessons start and finish at the tutor's building at the scheduled times. Travel time to and from the lesson destination counts as lesson time." },
      { t: 'Rescheduling into premium slots',
        d: 'Rescheduling into a higher-priced time zone (evening or weekend) requires payment of the difference.' },
      { t: 'Tutor cancellations',
        d: 'In the unlikely event the tutor needs to cancel, opportunities to reschedule will be provided.' },
    ],
    packageTitle: 'Lesson package expiry',
    packageLede: 'Prepaid lesson packages must be used within the following windows:',
    pkgLessons: 'Lessons in package',
    pkgExpiry: 'Must be used within',
    pkgLessonWord: 'lesson',
    pkgDaysWord: 'days',
  },
  privacy: {
    eyebrow: 'Privacy policy',
    title: 'Privacy policy',
    lede: 'A short, plain-language summary of how I handle your personal information, aligned with GDPR.',
    sections: [
      { t: 'What I collect',
        d: 'When you register for a lesson or contact me, I collect your name, email address, phone number, and any notes you share about your learning goals. If we meet for lessons, I may keep brief notes on your progress.' },
      { t: 'Why I collect it',
        d: 'To schedule and deliver lessons, communicate with you about bookings and rescheduling, issue invoices, and tailor lesson materials to your level and goals.' },
      { t: 'How long I keep it',
        d: 'Active student records are kept for as long as you are a student, plus 12 months. Invoice and payment records are kept for 5 years as required by Polish tax law. You can ask me to delete the rest at any time.' },
      { t: 'Who I share it with',
        d: 'Nobody, with two exceptions: my accountant (for invoicing and tax) and, if legally required, Polish tax authorities. I do not sell, rent, or share your data with any third-party marketers.' },
      { t: 'Your rights under GDPR',
        d: 'You have the right to access the data I hold on you, to correct it, to request its deletion, to export it, and to withdraw consent at any time. To exercise any of these rights, email me and I will respond within 30 days.' },
      { t: 'Cookies & analytics',
        d: 'This website uses only essential cookies needed for the language and preference toggles to work. No tracking pixels, no third-party analytics, no advertising cookies.' },
      { t: 'Contact',
        d: "Data controller: Andrew, Poznań, Poland. For any privacy-related questions or requests, use the email address in the Contact section." },
    ],
    draftNote: 'This policy is provided in good faith and may be updated. For complex processing questions, consult a qualified legal adviser.',
  },
};

const LEGAL_PL = {
  updated: 'Ostatnia aktualizacja',
  updatedDate: '22 kwietnia 2026',
  questions: 'Pytania? Napisz do mnie →',
  close: 'Zamknij',
  terms: {
    eyebrow: 'Regulamin',
    title: 'Regulamin',
    lede: 'Regulamin powstał na podstawie dotychczasowych doświadczeń — aby szanować i zabezpieczać czas, zarówno lektora, jak i uczniów.',
    items: [
      { t: 'Płatność z góry',
        d: 'Płatności są wymagane z góry, w polskich złotych (PLN).' },
      { t: 'Rozliczenie miesięczne',
        d: 'Płatności miesięczne należy uregulować do 1. dnia każdego miesiąca lub w innym wcześniej ustalonym dniu (np. 10.).' },
      { t: 'Ważność lekcji',
        d: 'Lekcje miesięczne wygasają z końcem miesiąca. Pakiety lekcji wygasają według poniższego harmonogramu.' },
      { t: 'Anulowanie z 24-godzinnym wyprzedzeniem',
        d: 'Anulowanie lub przełożenie lekcji wymaga co najmniej 24-godzinnego wyprzedzenia.' },
      { t: 'Opuszczone lekcje',
        d: 'Opuszczone lekcje przepadają.' },
      { t: 'Punktualność',
        d: 'Lekcje zaczynają się i kończą o ustalonej godzinie. Jeśli uczeń się spóźni, ten czas przepada bez obniżenia ceny.' },
      { t: 'Lekcje z dojazdem',
        d: 'Lekcje lokalne rozpoczynają się i kończą w budynku lektora o ustalonych godzinach. Czas dojazdu na miejsce i z powrotem wlicza się do czasu lekcji.' },
      { t: 'Zmiana na droższy slot',
        d: 'Przełożenie lekcji na droższą porę (wieczór lub weekend) wymaga dopłaty różnicy w cenie.' },
      { t: 'Anulowanie przez lektora',
        d: 'W mało prawdopodobnym przypadku, gdy lektor musi odwołać lekcję, zostanie zaproponowany nowy termin.' },
    ],
    packageTitle: 'Ważność pakietów lekcji',
    packageLede: 'Opłacone z góry pakiety lekcji muszą zostać wykorzystane w następujących terminach:',
    pkgLessons: 'Lekcji w pakiecie',
    pkgExpiry: 'Do wykorzystania w ciągu',
    pkgLessonWord: 'lekcja',
    pkgDaysWord: 'dni',
  },
  privacy: {
    eyebrow: 'Polityka prywatności',
    title: 'Polityka prywatności',
    lede: 'Krótkie, zrozumiałe podsumowanie tego, jak przetwarzam Twoje dane osobowe — zgodnie z RODO.',
    sections: [
      { t: 'Jakie dane zbieram',
        d: 'Przy rejestracji lub kontakcie zbieram imię i nazwisko, adres e-mail, numer telefonu oraz notatki, którymi się dzielisz odnośnie swoich celów nauki. W trakcie lekcji mogę prowadzić krótkie notatki z postępów.' },
      { t: 'W jakim celu',
        d: 'Aby planować i prowadzić lekcje, kontaktować się w sprawie rezerwacji i zmian, wystawiać faktury oraz dostosowywać materiały do Twojego poziomu i celów.' },
      { t: 'Jak długo przechowuję',
        d: 'Dane aktywnych uczniów przechowuję tak długo, jak trwa współpraca, plus 12 miesięcy. Faktury i dokumenty płatnicze — 5 lat, zgodnie z polskim prawem podatkowym. Pozostałe dane możesz usunąć w dowolnym momencie.' },
      { t: 'Komu udostępniam',
        d: 'Nikomu, z dwoma wyjątkami: księgowej (na potrzeby faktur i podatków) oraz — jeśli wymaga tego prawo — polskim organom skarbowym. Nie sprzedaję, nie wynajmuję ani nie udostępniam Twoich danych marketerom.' },
      { t: 'Twoje prawa (RODO)',
        d: 'Masz prawo dostępu do swoich danych, ich poprawiania, usunięcia, przeniesienia oraz wycofania zgody w dowolnym momencie. Aby skorzystać z tych praw, napisz do mnie — odpowiem w ciągu 30 dni.' },
      { t: 'Pliki cookie i analityka',
        d: 'Strona używa wyłącznie niezbędnych plików cookie — do zapamiętania języka i preferencji. Bez pikseli śledzących, bez zewnętrznej analityki, bez reklam.' },
      { t: 'Kontakt',
        d: 'Administrator danych: Andrew, Poznań, Polska. W sprawach prywatności napisz na adres e-mail z sekcji Kontakt.' },
    ],
    draftNote: 'Polityka przygotowana w dobrej wierze i może być aktualizowana. W kwestiach złożonych skonsultuj się z doradcą prawnym.',
  },
};

Object.assign(window, { Portrait, FaqList, PriceCalculator, RegistrationForm, Chatbot, Field, LegalModal });
