const { useState, useEffect, useRef } = React;

function NewBon() {
  const { navigate, t, profile } = window.useApp();
  const [errors, setErrors] = useState({});
  const [form, setForm] = useState(() => {
    const p = profile || {};
    return {
      clientName: '', clientPhone: '',
      reservationDate: today(), reservationTime: now(),
      pickupDate: today(), pickupTime: '',
      pickupAddress: '', dropoffAddress: '',
      plate: p.defaultPlate || '',
      passengers: '1',
      priceTTC: '', priceHT: '',
    };
  });

  function today() {
    return new Date().toISOString().slice(0, 10);
  }
  function now() {
    const d = new Date();
    return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
  }

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  // Auto-compute HT from TTC (TVA 10% for transport — user can override)
  const handleTTC = (v) => {
    set('priceTTC', v);
    const n = parseFloat(v);
    if (!isNaN(n)) set('priceHT', (n / 1.1).toFixed(2));
    else set('priceHT', '');
  };

  const validate = () => {
    const e = {};
    if (!form.clientName.trim()) e.clientName = true;
    if (!form.pickupAddress.trim()) e.pickupAddress = true;
    if (!form.dropoffAddress.trim()) e.dropoffAddress = true;
    if (!form.pickupDate) e.pickupDate = true;
    if (!form.pickupTime) e.pickupTime = true;
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handlePreview = () => {
    if (!validate()) return;
    const id = storage.nextBonId();
    const bon = { ...form, id, createdAt: new Date().toISOString(), profile: { ...profile } };
    navigate('preview', { bon });
  };

  return (
    <div style={ns.screen}>
      {/* Header */}
      <div style={ns.header}>
        <button style={ns.backBtn} onClick={() => navigate('home')}>
          <ChevLeft /> {t('cancel')}
        </button>
        <span style={ns.headerTitle}>{t('newBon')}</span>
        <div style={{ width: 70 }}></div>
      </div>

      <div style={ns.body}>
        {/* Driver summary */}
        <div style={ns.profileRow}>
          <div style={ns.avatar}>{(profile?.companyName || 'VTC').slice(0, 2).toUpperCase()}</div>
          <div style={ns.profileInfo}>
            <div style={ns.profileName}>{profile?.companyName || '—'}</div>
            <div style={ns.profileSub}>{profile?.evtc ? `EVTC ${profile.evtc}` : ''}{profile?.siret ? ` · ${profile.siret.slice(0,9)}` : ''}</div>
          </div>
          <button style={ns.editLink} onClick={() => navigate('profile')}>{t('edit')}</button>
        </div>

        {/* Client */}
        <Section label={t('sectionClient')}>
          <Field label={t('clientName')} value={form.clientName} onChange={v => set('clientName', v)}
            placeholder="Jean Martin" required error={errors.clientName} />
          <Field label={t('clientPhone')} value={form.clientPhone} onChange={v => set('clientPhone', v)}
            placeholder="06 12 34 56 78" type="tel" />
        </Section>

        {/* Reservation */}
        <Section label={t('sectionReservation')}>
          <Row>
            <Field label={t('reservationDate')} value={form.reservationDate} onChange={v => set('reservationDate', v)} type="date" half />
            <Field label={t('reservationTime')} value={form.reservationTime} onChange={v => set('reservationTime', v)} type="time" half />
          </Row>
          <Row>
            <Field label={t('pickupDate')} value={form.pickupDate} onChange={v => set('pickupDate', v)}
              type="date" half required error={errors.pickupDate} />
            <Field label={t('pickupTime')} value={form.pickupTime} onChange={v => set('pickupTime', v)}
              type="time" half required error={errors.pickupTime} />
          </Row>
        </Section>

        {/* Course */}
        <Section label={t('sectionCourse')}>
          <Field label={t('pickupAddress')} value={form.pickupAddress} onChange={v => set('pickupAddress', v)}
            placeholder="12 rue de Rivoli, Paris 1er" required error={errors.pickupAddress} icon="📍" />
          <Field label={t('dropoffAddress')} value={form.dropoffAddress} onChange={v => set('dropoffAddress', v)}
            placeholder="Aéroport CDG Terminal 2" required error={errors.dropoffAddress} icon="🏁" />
          <Row>
            <Field label={t('plate')} value={form.plate} onChange={v => set('plate', v)}
              placeholder="AB-123-CD" half />
            <Field label={t('passengers')} value={form.passengers} onChange={v => set('passengers', v)}
              type="number" min="1" max="8" placeholder="1" half />
          </Row>
        </Section>

        {/* Price */}
        <Section label={t('sectionPrice')}>
          <Row>
            <Field label={t('priceTTC')} value={form.priceTTC} onChange={handleTTC}
              type="number" placeholder="85.00" step="0.01" half icon="€" />
            <Field label={t('priceHT')} value={form.priceHT} onChange={v => set('priceHT', v)}
              type="number" placeholder="77.27" step="0.01" half icon="€" />
          </Row>
        </Section>
      </div>

      {/* Bottom CTA */}
      <div style={ns.bottomBar}>
        {Object.keys(errors).length > 0 && (
          <div style={ns.errorMsg}>{t('requiredFields')}</div>
        )}
        <button style={ns.previewBtn} onClick={handlePreview}>
          {t('preview')} →
        </button>
      </div>
    </div>
  );
}

function Section({ label, children }) {
  return (
    <div style={ns.section}>
      <div style={ns.sectionLabel}>{label}</div>
      <div style={ns.sectionBody}>{children}</div>
    </div>
  );
}

function Row({ children }) {
  return <div style={{ display: 'flex', gap: 10 }}>{children}</div>;
}

function Field({ label, value, onChange, placeholder, type = 'text', half, required, error, icon, min, max, step }) {
  return (
    <div style={{ flex: half ? 1 : undefined, minWidth: 0 }}>
      <label style={ns.fieldLabel}>
        {label}{required && <span style={{ color: 'var(--gold)' }}> *</span>}
      </label>
      <div style={{ position: 'relative' }}>
        {icon && <span style={ns.fieldIcon}>{icon}</span>}
        <input
          style={{ ...ns.input, ...(error ? ns.inputError : {}), ...(icon ? { paddingLeft: 28 } : {}) }}
          type={type} value={value} placeholder={placeholder}
          min={min} max={max} step={step}
          onChange={e => onChange(e.target.value)}
        />
      </div>
    </div>
  );
}

function ChevLeft() {
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ verticalAlign: 'middle' }}>
      <polyline points="15 18 9 12 15 6"/>
    </svg>
  );
}

const ns = {
  screen: { display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg)' },
  header: {
    background: 'var(--surface)', borderBottom: '1px solid var(--border)',
    padding: '0 16px', height: 56, paddingTop: 'var(--safe-top)',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    flexShrink: 0,
  },
  headerTitle: { fontSize: 16, fontWeight: 700, color: 'var(--text)' },
  backBtn: { background: 'none', border: 'none', color: 'var(--text-2)', fontSize: 14, fontFamily: 'var(--font)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 2, width: 70 },
  body: { flex: 1, overflowY: 'auto', padding: '16px', paddingBottom: 90, display: 'flex', flexDirection: 'column', gap: 16 },
  profileRow: { background: 'var(--surface)', borderRadius: 'var(--radius)', padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12, border: '1px solid var(--border)', boxShadow: 'var(--shadow)', flexShrink: 0 },
  avatar: { width: 40, height: 40, borderRadius: 10, background: 'var(--dark)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 800, flexShrink: 0 },
  profileInfo: { flex: 1, minWidth: 0 },
  profileName: { fontSize: 14, fontWeight: 700, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
  profileSub: { fontSize: 12, color: 'var(--text-2)', marginTop: 1 },
  editLink: { background: 'none', border: 'none', color: 'var(--gold)', fontSize: 13, fontFamily: 'var(--font)', cursor: 'pointer', fontWeight: 600 },
  section: { background: 'var(--surface)', borderRadius: 'var(--radius)', border: '1px solid var(--border)', boxShadow: 'var(--shadow)', flexShrink: 0 },
  sectionLabel: { fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.8px', color: 'var(--text-3)', padding: '9px 14px', background: 'var(--surface-2)', borderBottom: '1px solid var(--border)', borderRadius: 'var(--radius) var(--radius) 0 0' },
  sectionBody: { padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 10 },
  fieldLabel: { display: 'block', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', marginBottom: 5 },
  fieldIcon: { position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', fontSize: 14, pointerEvents: 'none' },
  input: {
    width: '100%', padding: '10px 12px', fontSize: 15,
    fontFamily: 'var(--font)', color: 'var(--text)',
    background: 'var(--bg)', border: '1.5px solid var(--border)',
    borderRadius: 'var(--radius-sm)', outline: 'none',
    appearance: 'none', WebkitAppearance: 'none',
    boxSizing: 'border-box',
  },
  inputError: { borderColor: '#ef4444', background: '#fff5f5' },
  bottomBar: { padding: '12px 16px', paddingBottom: 'calc(12px + var(--safe-bottom))', background: 'var(--surface)', borderTop: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0 },
  previewBtn: { background: 'var(--dark)', color: '#fff', border: 'none', borderRadius: 'var(--radius)', padding: '14px', fontSize: 16, fontWeight: 700, fontFamily: 'var(--font)', cursor: 'pointer', width: '100%' },
  errorMsg: { fontSize: 13, color: '#ef4444', textAlign: 'center' },
};

Object.assign(window, { NewBon });
