// BrokerProfilePage — Page de profil courtier (PR 2.1 Vague 2)
// Route : #/courtier/profil
// Suffixe alias : BP (BrokerProfile)
//
// Convention Vestora : pas d'import/export ES, React en global,
// composant exposé sur window.

const {
  useState: useBP,
  useEffect: useEBP,
  useRef: useRBP,
  useMemo: useMBP,
} = React;

const _HEX_BP = /^#[0-9A-Fa-f]{6}$/;
const _OACIQ_BP = /^[A-Z0-9]+$/;
const MAX_LOGO_KB_BP = 200;
const ALLOWED_LOGO_MIMES_BP = ['image/png', 'image/jpeg', 'image/jpg', 'image/svg+xml'];

function BrokerProfilePage({ user, lang }) {
  const FR = lang !== 'en';

  // ── Gating tier (mêmes patterns que BrokerDashboard) ─────────────────────
  const [tier, setTier] = useBP(null);
  useEBP(() => {
    const tg = window.vestora && window.vestora.tierGate;
    if (tg && typeof tg.getCurrentTier === 'function') {
      tg.getCurrentTier().then(t => setTier(t));
    } else {
      setTier('decouverte');
    }
  }, []);

  // ── Etat formulaire ────────────────────────────────────────────────────────
  const [form, setForm] = useBP({
    displayName: '',
    oaciqNumber: '',
    agency: '',
    phone: '',
    emailPublic: '',
    brandColor: '#0F172A',
    tagline: '',
    disclaimerExtra: '',
    logoUrl: '',
  });
  const [loading, setLoading] = useBP(true);
  const [saving, setSaving] = useBP(false);
  const [uploadingLogo, setUploadingLogo] = useBP(false);
  const [toast, setToast] = useBP(null); // { type: 'success'|'error', msg: string }
  const [errors, setErrors] = useBP({});
  const fileInputRef = useRBP(null);

  // ── Chargement initial profil ────────────────────────────────────────────
  useEBP(() => {
    if (tier !== 'pro' && tier !== 'entreprise') return;
    const api = window.vestora && window.vestora.brokerApi;
    if (!api || !api.getProfile) {
      setLoading(false);
      return;
    }
    let cancelled = false;
    api.getProfile().then(res => {
      if (cancelled) return;
      if (res.ok && res.data) {
        setForm(prev => ({ ...prev, ...res.data }));
      }
      // 404 = pas encore de profil — on garde le formulaire vide. Pas d'erreur.
      setLoading(false);
    });
    return () => { cancelled = true; };
  }, [tier]);

  // ── Toast auto-dismiss ───────────────────────────────────────────────────
  useEBP(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 4000);
    return () => clearTimeout(t);
  }, [toast]);

  // ── Helpers UI ───────────────────────────────────────────────────────────
  const set = (field) => (e) => {
    const v = e && e.target ? e.target.value : e;
    setForm(prev => ({ ...prev, [field]: v }));
    // Clear error sur edit
    setErrors(prev => prev[field] ? { ...prev, [field]: undefined } : prev);
  };

  const validate = () => {
    const errs = {};
    if (!form.displayName || !form.displayName.trim()) {
      errs.displayName = FR ? 'Nom requis.' : 'Display name required.';
    }
    if (form.oaciqNumber && form.oaciqNumber.trim()) {
      if (!_OACIQ_BP.test(form.oaciqNumber.trim().toUpperCase())) {
        errs.oaciqNumber = FR
          ? 'Format invalide (lettres/chiffres majuscules, ex: A1B2C3).'
          : 'Invalid format (uppercase letters/digits).';
      }
    }
    if (!_HEX_BP.test(form.brandColor || '')) {
      errs.brandColor = FR ? 'Format hex requis (#RRGGBB).' : 'Hex format required (#RRGGBB).';
    }
    return errs;
  };

  const handleSave = async () => {
    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length > 0) {
      setToast({ type: 'error', msg: FR ? 'Corrigez les erreurs ci-dessous.' : 'Fix the errors below.' });
      return;
    }
    const api = window.vestora && window.vestora.brokerApi;
    if (!api || !api.updateProfile) {
      setToast({ type: 'error', msg: 'API indisponible.' });
      return;
    }
    setSaving(true);
    const res = await api.updateProfile(form);
    setSaving(false);
    if (res.ok) {
      setForm(prev => ({ ...prev, ...res.data }));
      setToast({ type: 'success', msg: FR ? 'Profil enregistré ✓' : 'Profile saved ✓' });
    } else {
      const msg = (res.error && res.error.message) || 'Erreur inconnue';
      setToast({ type: 'error', msg: (FR ? 'Erreur : ' : 'Error: ') + msg });
    }
  };

  const handleLogoPick = () => {
    if (fileInputRef.current) fileInputRef.current.click();
  };

  const handleLogoChange = async (e) => {
    const file = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!file) return;
    // Validation client
    if (!ALLOWED_LOGO_MIMES_BP.includes(file.type)) {
      setToast({
        type: 'error',
        msg: FR ? 'Formats acceptés : PNG, JPG, SVG.' : 'Allowed formats: PNG, JPG, SVG.',
      });
      return;
    }
    if (file.size > MAX_LOGO_KB_BP * 1024) {
      setToast({
        type: 'error',
        msg: FR
          ? 'Logo trop volumineux (max ' + MAX_LOGO_KB_BP + ' KB).'
          : 'Logo too large (max ' + MAX_LOGO_KB_BP + ' KB).',
      });
      return;
    }
    // Le profil doit exister avant l'upload (sinon 409)
    if (!form.displayName || !form.displayName.trim()) {
      setToast({
        type: 'error',
        msg: FR
          ? 'Renseignez et enregistrez votre nom avant d’uploader un logo.'
          : 'Save your display name before uploading a logo.',
      });
      return;
    }

    const api = window.vestora && window.vestora.brokerApi;
    if (!api || !api.uploadLogo) return;

    setUploadingLogo(true);
    const res = await api.uploadLogo(file);
    setUploadingLogo(false);
    if (res.ok && res.data && res.data.logoUrl) {
      setForm(prev => ({ ...prev, logoUrl: res.data.logoUrl }));
      setToast({ type: 'success', msg: FR ? 'Logo téléversé ✓' : 'Logo uploaded ✓' });
    } else {
      const msg = (res.error && res.error.message) || 'Upload échoué';
      // Cas 409 : le profil n'existait pas cote DB
      if (res.error && res.error.status === 409) {
        setToast({
          type: 'error',
          msg: FR
            ? 'Enregistrez d’abord votre profil (bouton Enregistrer).'
            : 'Save your profile first.',
        });
      } else {
        setToast({ type: 'error', msg: (FR ? 'Erreur : ' : 'Error: ') + msg });
      }
    }
  };

  // ── Aperçu signature (mémoïsé) ───────────────────────────────────────────
  const preview = useMBP(() => ({
    displayName: form.displayName || (FR ? 'Votre nom' : 'Your name'),
    agency: form.agency || (FR ? 'Votre agence' : 'Your agency'),
    tagline: form.tagline || (FR ? 'Votre slogan apparaîtra ici' : 'Your tagline will appear here'),
    phone: form.phone || '',
    emailPublic: form.emailPublic || '',
    oaciqNumber: form.oaciqNumber || '',
    logoUrl: form.logoUrl || '',
    brandColor: _HEX_BP.test(form.brandColor || '') ? form.brandColor : '#0F172A',
  }), [form, FR]);

  // ── Loading state ─────────────────────────────────────────────────────────
  if (tier === null) {
    return (
      <div className="broker-spinner-wrap" aria-label={FR ? 'Chargement…' : 'Loading…'}>
        <div className="broker-spinner" />
      </div>
    );
  }

  // ── Gating non Pro ────────────────────────────────────────────────────────
  if (tier !== 'pro' && tier !== 'entreprise') {
    return (
      <div style={{ padding: 40, textAlign: 'center', color: 'var(--ink-2)', minHeight: '60vh' }}>
        <div style={{ fontSize: 36, marginBottom: 12 }}>🔒</div>
        <p style={{ maxWidth: 380, margin: '0 auto 16px', lineHeight: 1.6 }}>
          {FR
            ? 'Le profil courtier est réservé au plan Pro Vestora.'
            : 'Broker profile is reserved to the Pro plan.'}
        </p>
        <button
          onClick={() => window.navigateTo('#/tarifs')}
          style={{
            padding: '10px 24px', borderRadius: 8, background: 'var(--accent)',
            color: 'var(--accent-fg)', border: 'none', cursor: 'pointer', fontWeight: 600,
          }}
        >
          {FR ? 'Voir les plans' : 'See plans'}
        </button>
      </div>
    );
  }

  // ── Rendu page ────────────────────────────────────────────────────────────
  const inputStyle = {
    width: '100%', padding: '10px 12px', borderRadius: 8,
    border: '1px solid var(--border, #d1d5db)', background: 'var(--card, #fff)',
    color: 'var(--ink, #0f172a)', fontSize: 14, boxSizing: 'border-box',
  };
  const labelStyle = {
    display: 'block', fontSize: 13, fontWeight: 600, color: 'var(--ink, #0f172a)',
    marginBottom: 6,
  };
  const helpStyle = { fontSize: 12, color: 'var(--ink-2, #64748b)', marginTop: 4 };
  const errStyle = { fontSize: 12, color: '#dc2626', marginTop: 4 };

  return (
    <div className="broker-root broker-profile-root" style={{ background: 'var(--bg, #f8fafc)', minHeight: '100vh' }}>
      {/* Header */}
      <div className="broker-header">
        <div className="broker-header-left">
          <button
            className="broker-back-btn"
            onClick={() => window.navigateTo('#/courtier')}
            aria-label={FR ? 'Retour' : 'Back'}
          >
            <svg width="14" height="14" viewBox="0 0 14 14" stroke="currentColor" strokeWidth="1.8" fill="none">
              <path d="M9 2L3 7l6 5"/>
            </svg>
            {FR ? 'Retour' : 'Back'}
          </button>
          <span className="broker-header-title">
            {FR ? 'Mon profil courtier' : 'My broker profile'}
          </span>
        </div>
        <div className="broker-header-right">
          {user && (
            <span className="broker-user-chip">{user.email || (FR ? 'Courtier' : 'Broker')}</span>
          )}
          <span className="broker-tier-badge">Pro</span>
        </div>
      </div>

      {loading ? (
        <div className="broker-spinner-wrap" style={{ padding: 40 }}>
          <div className="broker-spinner" />
        </div>
      ) : (
        <div style={{
          maxWidth: 1100, margin: '0 auto', padding: '24px 20px',
          display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) minmax(280px, 380px)',
          gap: 24, alignItems: 'start',
        }}>
          {/* ── Colonne formulaire ──────────────────────────────────────── */}
          <div style={{
            background: 'var(--card, #fff)', border: '1px solid var(--border, #e5e7eb)',
            borderRadius: 12, padding: 24,
          }}>
            <h2 style={{ margin: '0 0 4px', fontSize: 18, color: 'var(--ink, #0f172a)' }}>
              {FR ? 'Identité et branding' : 'Identity and branding'}
            </h2>
            <p style={{ margin: '0 0 20px', fontSize: 13, color: 'var(--ink-2, #64748b)' }}>
              {FR
                ? 'Ces informations apparaîtront sur vos fiches PDF brandées et dans le portail client.'
                : 'This information will appear on your branded PDFs and the client portal.'}
            </p>

            {/* Logo */}
            <div style={{ marginBottom: 20 }}>
              <span style={labelStyle}>{FR ? 'Logo' : 'Logo'}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <div style={{
                  width: 80, height: 80, borderRadius: 12,
                  border: '1px dashed var(--border, #d1d5db)',
                  background: 'var(--bg, #f8fafc)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  overflow: 'hidden', flexShrink: 0,
                }}>
                  {form.logoUrl ? (
                    <img
                      src={form.logoUrl}
                      alt={FR ? 'Logo courtier' : 'Broker logo'}
                      style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
                    />
                  ) : (
                    <span style={{ fontSize: 11, color: 'var(--ink-2, #94a3b8)', textAlign: 'center', padding: 4 }}>
                      {FR ? 'Aucun logo' : 'No logo'}
                    </span>
                  )}
                </div>
                <div>
                  <button
                    type="button"
                    onClick={handleLogoPick}
                    disabled={uploadingLogo}
                    style={{
                      padding: '8px 16px', borderRadius: 8, fontSize: 13, fontWeight: 600,
                      background: 'var(--card, #fff)', color: 'var(--ink, #0f172a)',
                      border: '1px solid var(--border, #d1d5db)',
                      cursor: uploadingLogo ? 'wait' : 'pointer',
                    }}
                  >
                    {uploadingLogo
                      ? (FR ? 'Téléversement…' : 'Uploading…')
                      : (FR ? 'Choisir un logo' : 'Choose a logo')}
                  </button>
                  <input
                    ref={fileInputRef}
                    type="file"
                    accept="image/png,image/jpeg,image/svg+xml"
                    style={{ display: 'none' }}
                    onChange={handleLogoChange}
                  />
                  <div style={helpStyle}>
                    {FR
                      ? 'PNG, JPG ou SVG. Max 200 KB.'
                      : 'PNG, JPG or SVG. Max 200 KB.'}
                  </div>
                </div>
              </div>
            </div>

            {/* Display name */}
            <div style={{ marginBottom: 16 }}>
              <label style={labelStyle} htmlFor="bp-displayName">
                {FR ? 'Nom à afficher *' : 'Display name *'}
              </label>
              <input
                id="bp-displayName"
                style={inputStyle}
                value={form.displayName}
                onChange={set('displayName')}
                maxLength={256}
                placeholder={FR ? 'Ex : Alain Ouellette' : 'e.g. Alain Ouellette'}
              />
              {errors.displayName && <div style={errStyle}>{errors.displayName}</div>}
            </div>

            {/* OACIQ */}
            <div style={{ marginBottom: 16 }}>
              <label style={labelStyle} htmlFor="bp-oaciq">
                {FR ? 'Numéro OACIQ' : 'OACIQ number'}
              </label>
              <input
                id="bp-oaciq"
                style={inputStyle}
                value={form.oaciqNumber}
                onChange={set('oaciqNumber')}
                maxLength={64}
                placeholder="A1B2C3"
              />
              <div style={helpStyle}>
                {FR
                  ? 'Affiché tel quel sur vos fiches PDF (pas de vérification OACIQ live).'
                  : 'Displayed as-is on PDFs (no OACIQ live verification).'}
              </div>
              {errors.oaciqNumber && <div style={errStyle}>{errors.oaciqNumber}</div>}
            </div>

            {/* Agency */}
            <div style={{ marginBottom: 16 }}>
              <label style={labelStyle} htmlFor="bp-agency">
                {FR ? 'Agence' : 'Agency'}
              </label>
              <input
                id="bp-agency"
                style={inputStyle}
                value={form.agency}
                onChange={set('agency')}
                maxLength={256}
                placeholder={FR ? 'Ex : Royal LePage Québec' : 'e.g. Royal LePage Quebec'}
              />
            </div>

            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16,
            }}>
              <div>
                <label style={labelStyle} htmlFor="bp-phone">{FR ? 'Téléphone' : 'Phone'}</label>
                <input
                  id="bp-phone"
                  style={inputStyle}
                  value={form.phone}
                  onChange={set('phone')}
                  maxLength={64}
                  placeholder="418-555-1234"
                />
              </div>
              <div>
                <label style={labelStyle} htmlFor="bp-emailPublic">
                  {FR ? 'Courriel public' : 'Public email'}
                </label>
                <input
                  id="bp-emailPublic"
                  style={inputStyle}
                  type="email"
                  value={form.emailPublic}
                  onChange={set('emailPublic')}
                  maxLength={256}
                  placeholder="contact@agence.ca"
                />
              </div>
            </div>

            {/* Tagline */}
            <div style={{ marginBottom: 16 }}>
              <label style={labelStyle} htmlFor="bp-tagline">
                {FR ? 'Slogan (1 ligne)' : 'Tagline (1 line)'}
              </label>
              <input
                id="bp-tagline"
                style={inputStyle}
                value={form.tagline}
                onChange={set('tagline')}
                maxLength={256}
                placeholder={FR
                  ? 'Ex : Investissement immobilier QC depuis 2010'
                  : 'e.g. Quebec real estate investment since 2010'}
              />
            </div>

            {/* Brand color */}
            <div style={{ marginBottom: 16 }}>
              <label style={labelStyle} htmlFor="bp-brandColor">
                {FR ? 'Couleur de marque' : 'Brand color'}
              </label>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <input
                  id="bp-brandColor"
                  type="color"
                  value={_HEX_BP.test(form.brandColor || '') ? form.brandColor : '#0F172A'}
                  onChange={set('brandColor')}
                  style={{ width: 48, height: 40, padding: 0, border: '1px solid var(--border, #d1d5db)', borderRadius: 8, cursor: 'pointer' }}
                />
                <input
                  type="text"
                  value={form.brandColor}
                  onChange={set('brandColor')}
                  style={{ ...inputStyle, maxWidth: 140 }}
                  maxLength={7}
                  placeholder="#0F172A"
                />
              </div>
              {errors.brandColor && <div style={errStyle}>{errors.brandColor}</div>}
            </div>

            {/* Disclaimer custom */}
            <div style={{ marginBottom: 20 }}>
              <label style={labelStyle} htmlFor="bp-disclaimer">
                {FR ? 'Avis personnalisé (ajout au bas des fiches)' : 'Custom disclaimer (added to PDFs)'}
              </label>
              <textarea
                id="bp-disclaimer"
                style={{ ...inputStyle, minHeight: 80, fontFamily: 'inherit', resize: 'vertical' }}
                value={form.disclaimerExtra}
                onChange={set('disclaimerExtra')}
                maxLength={4000}
                placeholder={FR
                  ? 'Ex : Membre de l’OACIQ. Les analyses présentées ne constituent pas un conseil financier.'
                  : 'e.g. OACIQ member. Analyses are not financial advice.'}
              />
              <div style={helpStyle}>
                {FR
                  ? 'S’ajoute au disclaimer Vestora standard sur les fiches PDF.'
                  : 'Appended to the standard Vestora disclaimer on PDFs.'}
              </div>
            </div>

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 12 }}>
              <button
                type="button"
                onClick={handleSave}
                disabled={saving}
                style={{
                  padding: '10px 24px', borderRadius: 8, fontSize: 14, fontWeight: 600,
                  background: saving ? 'var(--ink-2, #94a3b8)' : 'var(--accent, #0F172A)',
                  color: 'var(--accent-fg, #fff)', border: 'none',
                  cursor: saving ? 'wait' : 'pointer',
                }}
              >
                {saving
                  ? (FR ? 'Enregistrement…' : 'Saving…')
                  : (FR ? 'Enregistrer' : 'Save')}
              </button>
            </div>
          </div>

          {/* ── Colonne preview signature ───────────────────────────────── */}
          <div style={{ position: 'sticky', top: 24 }}>
            <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2, #64748b)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
              {FR ? 'Aperçu de votre signature' : 'Signature preview'}
            </div>
            <div style={{
              background: 'var(--card, #fff)', border: '1px solid var(--border, #e5e7eb)',
              borderRadius: 12, overflow: 'hidden',
              boxShadow: '0 2px 6px rgba(15,23,42,0.04)',
            }}>
              {/* Barre d'accent couleur de marque */}
              <div style={{ height: 6, background: preview.brandColor }} />
              <div style={{ padding: 16, display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{
                  width: 56, height: 56, borderRadius: 8,
                  background: 'var(--bg, #f1f5f9)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  overflow: 'hidden', flexShrink: 0,
                }}>
                  {preview.logoUrl ? (
                    <img src={preview.logoUrl} alt="" style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
                  ) : (
                    <span style={{ fontSize: 18, color: preview.brandColor, fontWeight: 700 }}>
                      {(preview.displayName || 'V').charAt(0).toUpperCase()}
                    </span>
                  )}
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink, #0f172a)' }}>
                    {preview.displayName}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-2, #64748b)', marginTop: 2 }}>
                    {preview.agency}
                  </div>
                  <div style={{ fontSize: 12, color: preview.brandColor, marginTop: 6, fontStyle: 'italic' }}>
                    {preview.tagline}
                  </div>
                  {(preview.phone || preview.emailPublic) && (
                    <div style={{ fontSize: 11, color: 'var(--ink-2, #64748b)', marginTop: 8 }}>
                      {preview.phone && <div>📞 {preview.phone}</div>}
                      {preview.emailPublic && <div>✉ {preview.emailPublic}</div>}
                    </div>
                  )}
                  {preview.oaciqNumber && (
                    <div style={{ fontSize: 10, color: 'var(--ink-2, #94a3b8)', marginTop: 6 }}>
                      OACIQ · {preview.oaciqNumber}
                    </div>
                  )}
                </div>
              </div>
            </div>
            <p style={{ fontSize: 11, color: 'var(--ink-2, #94a3b8)', marginTop: 8, lineHeight: 1.5 }}>
              {FR
                ? 'Cette mini-carte illustre comment votre signature apparaîtra sur les fiches PDF générées pour vos clients (PR 2.2).'
                : 'This preview shows how your signature will appear on client-facing PDFs (PR 2.2).'}
            </p>
          </div>
        </div>
      )}

      {/* ── Section Notifications (digest hebdo) — PR 4.2 Vague 4 ────────── */}
      {(tier === 'pro' || tier === 'entreprise') && (
        <BrokerDigestSettingsBP FR={FR} setToast={setToast} />
      )}

      {/* Toast */}
      {toast && (
        <div style={{
          position: 'fixed', bottom: 20, left: '50%', transform: 'translateX(-50%)',
          background: toast.type === 'success' ? '#16a34a' : '#dc2626',
          color: '#fff', padding: '12px 20px', borderRadius: 8, fontSize: 14,
          fontWeight: 500, boxShadow: '0 4px 14px rgba(0,0,0,0.2)', zIndex: 1000,
          maxWidth: 'calc(100% - 40px)',
        }} role="status" aria-live="polite">
          {toast.msg}
        </div>
      )}
    </div>
  );
}


// ─────────────────────────────────────────────────────────────────────────────
// BrokerDigestSettingsBP — section Notifications (PR 4.2 Vague 4)
// Toggle digest + jour/heure + bouton "Recevoir un test maintenant".
// ─────────────────────────────────────────────────────────────────────────────
const DAYS_LABEL_FR_BP = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
const DAYS_LABEL_EN_BP = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

function BrokerDigestSettingsBP({ FR, setToast }) {
  const [enabled, setEnabled] = useBP(true);
  const [dayOfWeek, setDayOfWeek] = useBP(1);
  const [hourLocal, setHourLocal] = useBP(8);
  const [tz, setTz] = useBP('America/Montreal');
  const [savingD, setSavingD] = useBP(false);
  const [sendingTest, setSendingTest] = useBP(false);
  const [loadedD, setLoadedD] = useBP(false);

  useEBP(() => {
    const api = window.vestora && window.vestora.brokerApi;
    if (!api || !api.getProfile) { setLoadedD(true); return; }
    let cancelled = false;
    api.getProfile().then(res => {
      if (cancelled) return;
      const d = res && res.data;
      if (d) {
        if (typeof d.digestEnabled === 'boolean') setEnabled(d.digestEnabled);
        else if (typeof d.digest_enabled === 'boolean') setEnabled(d.digest_enabled);
        const dow = d.digestDayOfWeek != null ? d.digestDayOfWeek : d.digest_day_of_week;
        if (typeof dow === 'number') setDayOfWeek(dow);
        const hr = d.digestHour != null ? d.digestHour : d.digest_hour;
        if (typeof hr === 'number') setHourLocal(hr);
        const z = d.digestTimezone || d.digest_timezone;
        if (z) setTz(z);
      }
      setLoadedD(true);
    });
    return () => { cancelled = true; };
  }, []);

  const saveSettings = async () => {
    setSavingD(true);
    try {
      const token = window.vestora && window.vestora.auth && window.vestora.auth.getAccessToken
        ? await window.vestora.auth.getAccessToken()
        : null;
      const cfg = (window.vestora && window.vestora.config) || {};
      const apiUrl = cfg.apiUrl || '';
      const res = await fetch(`${apiUrl}/api/v1/broker/digest/settings`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          ...(token ? { Authorization: `Bearer ${token}` } : {}),
        },
        body: JSON.stringify({
          enabled: enabled,
          day_of_week: dayOfWeek,
          hour_local: hourLocal,
          timezone: tz,
        }),
      });
      if (res.ok) {
        setToast({ type: 'success', msg: FR ? 'Preferences enregistrees.' : 'Preferences saved.' });
      } else {
        setToast({ type: 'error', msg: FR ? 'Erreur lors de l\'enregistrement.' : 'Save failed.' });
      }
    } catch (e) {
      setToast({ type: 'error', msg: String(e && e.message || e) });
    } finally {
      setSavingD(false);
    }
  };

  const sendTest = async () => {
    setSendingTest(true);
    try {
      const token = window.vestora && window.vestora.auth && window.vestora.auth.getAccessToken
        ? await window.vestora.auth.getAccessToken()
        : null;
      const cfg = (window.vestora && window.vestora.config) || {};
      const apiUrl = cfg.apiUrl || '';
      const res = await fetch(`${apiUrl}/api/v1/broker/digest/send-now`, {
        method: 'POST',
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      });
      if (res.ok) {
        const data = await res.json();
        if (data.status === 'sent') {
          setToast({ type: 'success', msg: FR ? `Test envoye (${data.alerts_count} biens).` : `Test sent (${data.alerts_count} listings).` });
        } else if (data.status === 'skipped') {
          setToast({ type: 'success', msg: FR ? 'Aucun match cette semaine — rien a envoyer.' : 'No matches this week — nothing to send.' });
        } else {
          setToast({ type: 'error', msg: data.error || (FR ? 'Echec envoi.' : 'Send failed.') });
        }
      } else if (res.status === 429) {
        setToast({ type: 'error', msg: FR ? 'Limite atteinte (5/heure). Reessayez plus tard.' : 'Rate limit (5/hour).' });
      } else {
        setToast({ type: 'error', msg: FR ? 'Echec envoi.' : 'Send failed.' });
      }
    } catch (e) {
      setToast({ type: 'error', msg: String(e && e.message || e) });
    } finally {
      setSendingTest(false);
    }
  };

  const labelStyle = { fontSize: 13, fontWeight: 500, color: 'var(--ink, #0f172a)', marginBottom: 6, display: 'block' };
  const inputStyle = {
    width: '100%', padding: '8px 10px', fontSize: 14,
    border: '1px solid var(--border, #e5e7eb)', borderRadius: 6,
    background: 'var(--card, #fff)', color: 'var(--ink, #0f172a)',
  };

  const DAYS = FR ? DAYS_LABEL_FR_BP : DAYS_LABEL_EN_BP;

  return (
    <div style={{
      marginTop: 32,
      background: 'var(--card, #fff)',
      border: '1px solid var(--border, #e5e7eb)',
      borderRadius: 12,
      padding: 24,
      boxShadow: '0 2px 6px rgba(15,23,42,0.04)',
    }}>
      <h2 style={{ fontSize: 16, fontWeight: 700, color: 'var(--ink, #0f172a)', margin: '0 0 4px' }}>
        {FR ? 'Notifications — Digest hebdo' : 'Notifications — Weekly digest'}
      </h2>
      <p style={{ fontSize: 13, color: 'var(--ink-2, #64748b)', margin: '0 0 20px', lineHeight: 1.5 }}>
        {FR
          ? 'Recevez chaque semaine un email brande Vestora avec les meilleurs nouveaux biens pour chacun de vos clients suivis.'
          : 'Receive a weekly Vestora-branded email with the top new matches for each tracked client.'}
      </p>

      {/* Toggle enabled */}
      <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 18, cursor: 'pointer' }}>
        <input
          type="checkbox"
          checked={enabled}
          onChange={(e) => setEnabled(e.target.checked)}
          style={{ width: 18, height: 18, cursor: 'pointer' }}
          aria-label={FR ? 'Activer le digest' : 'Enable digest'}
        />
        <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--ink, #0f172a)' }}>
          {FR ? 'Activer le digest hebdo' : 'Enable weekly digest'}
        </span>
      </label>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(180px,1fr))', gap: 16, marginBottom: 20 }}>
        <div>
          <label style={labelStyle}>{FR ? 'Jour' : 'Day'}</label>
          <select
            value={dayOfWeek}
            onChange={(e) => setDayOfWeek(parseInt(e.target.value, 10))}
            disabled={!enabled}
            style={inputStyle}
          >
            {DAYS.map((d, i) => (
              <option key={i} value={i}>{d}</option>
            ))}
          </select>
        </div>
        <div>
          <label style={labelStyle}>{FR ? 'Heure (locale)' : 'Hour (local)'}</label>
          <select
            value={hourLocal}
            onChange={(e) => setHourLocal(parseInt(e.target.value, 10))}
            disabled={!enabled}
            style={inputStyle}
          >
            {Array.from({ length: 24 }, (_, h) => (
              <option key={h} value={h}>{String(h).padStart(2, '0')}h00</option>
            ))}
          </select>
        </div>
        <div>
          <label style={labelStyle}>{FR ? 'Fuseau' : 'Timezone'}</label>
          <select
            value={tz}
            onChange={(e) => setTz(e.target.value)}
            disabled={!enabled}
            style={inputStyle}
          >
            <option value="America/Montreal">America/Montreal</option>
            <option value="America/Toronto">America/Toronto</option>
            <option value="America/Vancouver">America/Vancouver</option>
            <option value="America/Halifax">America/Halifax</option>
          </select>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <button
          type="button"
          onClick={saveSettings}
          disabled={savingD || !loadedD}
          style={{
            padding: '10px 18px',
            background: 'var(--ink, #0f172a)', color: '#e8c96d',
            border: 0, borderRadius: 6, fontSize: 14, fontWeight: 600,
            cursor: savingD ? 'wait' : 'pointer',
            opacity: savingD ? 0.6 : 1,
          }}
        >
          {savingD
            ? (FR ? 'Enregistrement…' : 'Saving…')
            : (FR ? 'Enregistrer les preferences' : 'Save preferences')}
        </button>
        <button
          type="button"
          onClick={sendTest}
          disabled={sendingTest}
          style={{
            padding: '10px 18px',
            background: 'transparent', color: 'var(--ink, #0f172a)',
            border: '1px solid var(--border, #cbd5e1)', borderRadius: 6,
            fontSize: 14, fontWeight: 600, cursor: sendingTest ? 'wait' : 'pointer',
            opacity: sendingTest ? 0.6 : 1,
          }}
        >
          {sendingTest
            ? (FR ? 'Envoi…' : 'Sending…')
            : (FR ? 'Recevoir un test maintenant' : 'Send a test now')}
        </button>
      </div>
    </div>
  );
}

window.BrokerProfilePage = BrokerProfilePage;
