const { useState, useRef } = React;

function Profile() {
  const { t, profile, updateProfile, lang, setLang: setAppLang } = window.useApp();
  const [form, setForm] = useState(() => profile || {
    companyName: '', address: '', evtc: '', siret: '', defaultPlate: '', logo: null
  });
  const [saved, setSaved] = useState(false);
  const fileRef = useRef();

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

  const handleSave = () => {
    updateProfile(form);
    setSaved(true);
    setTimeout(() => setSaved(false), 2500);
  };

  const handleLogo = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => set('logo', ev.target.result);
    reader.readAsDataURL(file);
  };

  const handleLangToggle = () => {
    const next = lang === 'fr' ? 'en' : 'fr';
    setAppLang(next);
    storage.setLang(next);
  };

  return (
    <div style={ps.screen}>
      <div style={ps.header}>
        <span style={ps.headerTitle}>{t('profileTitle')}</span>
      </div>

      <div style={ps.body}>
        {/* Logo */}
        <div style={ps.logoSection}>
          <div style={ps.logoPreview} onClick={() => fileRef.current.click()}>
            {form.logo
              ? <img src={form.logo} alt="logo" style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 10 }} />
              : <div style={ps.logoPlaceholder}>
                  <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="1.5" strokeLinecap="round">
                    <rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/>
                  </svg>
                  <span style={{ fontSize: 12, color: 'var(--text-3)', marginTop: 4 }}>{t('logoAdd')}</span>
                </div>
            }
          </div>
          {form.logo && (
            <div style={{ display: 'flex', gap: 8 }}>
              <button style={ps.logoBtn} onClick={() => fileRef.current.click()}>{t('logoChange')}</button>
              <button style={{ ...ps.logoBtn, color: '#ef4444' }} onClick={() => set('logo', null)}>✕</button>
            </div>
          )}
          <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }} onChange={handleLogo} />
        </div>

        {/* Company info */}
        <Section label={t('sectionDriver')}>
          <PField label={t('companyName')} value={form.companyName} onChange={v => set('companyName', v)} placeholder="Durairaj Ramalingam" required />
          <PField label={t('address')} value={form.address} onChange={v => set('address', v)} placeholder="12 av. Victor Hugo, 75016 Paris" />
          <PField label={t('evtc')} value={form.evtc} onChange={v => set('evtc', v)} placeholder="2024/75/1234" />
          <PField label={t('siret')} value={form.siret} onChange={v => set('siret', v)} placeholder="890 123 456 00017" />
          <PField label={t('defaultPlate')} value={form.defaultPlate} onChange={v => set('defaultPlate', v)} placeholder="AB-123-CD" />
        </Section>

        {/* Language */}
        <div style={ps.langSection}>
          <span style={ps.langLabel}>{t('language')}</span>
          <button style={ps.langToggle} onClick={handleLangToggle}>
            <span style={{ ...ps.langOpt, ...(lang === 'fr' ? ps.langOptActive : {}) }}>FR</span>
            <span style={{ ...ps.langOpt, ...(lang === 'en' ? ps.langOptActive : {}) }}>EN</span>
          </button>
        </div>
      </div>

      <div style={ps.bottomBar}>
        {saved && <div style={ps.savedMsg}>✓ {t('profileSaved')}</div>}
        <button style={ps.saveBtn} onClick={handleSave}>
          {t('save')}
        </button>
      </div>
    </div>
  );
}

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

function PField({ label, value, onChange, placeholder, required }) {
  return (
    <div>
      <label style={ps.fieldLabel}>
        {label}{required && <span style={{ color: 'var(--gold)' }}> *</span>}
      </label>
      <input
        style={ps.input}
        value={value || ''}
        placeholder={placeholder}
        onChange={e => onChange(e.target.value)}
      />
    </div>
  );
}

const ps = {
  screen: { display: 'flex', flexDirection: 'column', height: '100%', background: 'var(--bg)' },
  header: {
    background: 'var(--dark)', color: '#fff',
    padding: '16px 20px 18px',
    paddingTop: 'calc(16px + var(--safe-top))',
    flexShrink: 0,
  },
  headerTitle: { fontSize: 22, fontWeight: 700, letterSpacing: '-0.4px' },
  body: { flex: 1, overflowY: 'auto', padding: '16px', paddingBottom: 80, display: 'flex', flexDirection: 'column', gap: 16 },

  logoSection: { display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, paddingTop: 4 },
  logoPreview: {
    width: 100, height: 100, borderRadius: 14,
    border: '2px dashed var(--border)', background: 'var(--surface)',
    display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
    cursor: 'pointer', overflow: 'hidden',
  },
  logoPlaceholder: { display: 'flex', flexDirection: 'column', alignItems: 'center' },
  logoBtn: { background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 6, padding: '5px 12px', fontSize: 13, fontFamily: 'var(--font)', cursor: 'pointer', color: 'var(--text-2)' },

  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 },
  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' },

  langSection: { background: 'var(--surface)', borderRadius: 'var(--radius)', padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', border: '1px solid var(--border)', boxShadow: 'var(--shadow)', flexShrink: 0 },
  langLabel: { fontSize: 15, fontWeight: 600, color: 'var(--text)' },
  langToggle: { display: 'flex', background: 'var(--surface-2)', border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden', cursor: 'pointer', padding: 0 },
  langOpt: { padding: '6px 16px', fontSize: 14, fontFamily: 'var(--font)', fontWeight: 600, color: 'var(--text-2)', border: 'none', background: 'none', cursor: 'pointer', transition: 'all 0.15s' },
  langOptActive: { background: 'var(--dark)', color: '#fff', borderRadius: 7 },

  bottomBar: { padding: '12px 16px', paddingBottom: 'calc(12px + var(--safe-bottom))', background: 'var(--surface)', borderTop: '1px solid var(--border)', flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 8 },
  savedMsg: { textAlign: 'center', fontSize: 14, color: '#22c55e', fontWeight: 600 },
  saveBtn: { background: 'var(--dark)', color: '#fff', border: 'none', borderRadius: 'var(--radius)', padding: '14px', fontSize: 16, fontWeight: 700, fontFamily: 'var(--font)', cursor: 'pointer', width: '100%' },
};

Object.assign(window, { Profile });
