// BrokerAgendaPanel — onglet Agenda du dashboard courtier (Vague 5 PR 5.3).
//
// Liste des visites a venir (7 jours), formulaire de creation manuelle,
// declenchement de notifications natives (push) J-1/J-0 via le service
// worker PWA (PR 4.6) si window.notifyLocal disponible.
//
// Convention Vestora : pas d'import/export ES, React en global,
// composant exposé sur window.BrokerAgendaPanel.

(function () {
  const React = window.React;
  if (!React) return;
  const { useState, useEffect } = React;

  async function _fetch(path, opts) {
    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 || '';
    return fetch(apiUrl + path, Object.assign({}, opts, {
      headers: Object.assign(
        { 'Content-Type': 'application/json' },
        token ? { Authorization: 'Bearer ' + token } : {},
        (opts && opts.headers) || {}
      ),
    }));
  }

  function fmtWhen(iso, FR) {
    try {
      const d = new Date(iso);
      const opts = { weekday: 'short', day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' };
      return d.toLocaleString(FR ? 'fr-CA' : 'en-CA', opts);
    } catch (e) {
      return iso;
    }
  }

  function scheduleLocalNotif(visit, FR) {
    try {
      if (!window.notifyLocal) return;
      const when = new Date(visit.scheduled_at).getTime();
      const now = Date.now();
      // J-0 : 1h avant
      const trigger1h = when - 60 * 60 * 1000;
      if (trigger1h > now && trigger1h - now < 7 * 24 * 60 * 60 * 1000) {
        setTimeout(() => {
          window.notifyLocal(
            FR ? 'Visite dans 1h' : 'Visit in 1h',
            { body: visit.address }
          );
        }, trigger1h - now);
      }
    } catch (e) { /* noop */ }
  }

  function BrokerAgendaPanel({ lang }) {
    const FR = lang !== 'en';
    const [visits, setVisits] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showForm, setShowForm] = useState(false);
    const [form, setForm] = useState({
      scheduled_at: '',
      duration_minutes: 30,
      address: '',
      notes: '',
      visitor_name: '',
      visitor_email: '',
      visitor_phone: '',
      push_to_google: true,
    });
    const [saving, setSaving] = useState(false);

    const reload = async () => {
      setLoading(true);
      setError(null);
      try {
        const r = await _fetch('/api/v1/integrations/google_calendar/visits?days=14');
        if (!r.ok) {
          setError(FR ? 'Erreur de chargement.' : 'Load error.');
          setVisits([]);
          return;
        }
        const data = await r.json();
        const arr = (data && data.visits) || [];
        setVisits(arr);
        // Notifs natives (J-0 1h)
        arr.forEach(v => scheduleLocalNotif(v, FR));
      } catch (e) {
        setError(String(e && e.message || e));
        setVisits([]);
      } finally {
        setLoading(false);
      }
    };

    useEffect(() => { reload(); }, []);

    const submit = async (e) => {
      e.preventDefault();
      if (!form.scheduled_at || !form.address) return;
      setSaving(true);
      try {
        const payload = Object.assign({}, form, {
          scheduled_at: new Date(form.scheduled_at).toISOString(),
        });
        const r = await _fetch('/api/v1/integrations/google_calendar/visits', {
          method: 'POST',
          body: JSON.stringify(payload),
        });
        if (!r.ok) {
          const d = await r.json().catch(() => ({}));
          setError((d && d.detail) || (FR ? 'Erreur creation.' : 'Create error.'));
          return;
        }
        setShowForm(false);
        setForm({
          scheduled_at: '', duration_minutes: 30, address: '', notes: '',
          visitor_name: '', visitor_email: '', visitor_phone: '', push_to_google: true,
        });
        await reload();
      } finally {
        setSaving(false);
      }
    };

    const cancel = async (visitId) => {
      if (!window.confirm(FR ? 'Annuler cette visite ?' : 'Cancel this visit?')) return;
      const r = await _fetch('/api/v1/integrations/google_calendar/visits/' + visitId, {
        method: 'PATCH',
        body: JSON.stringify({ status: 'cancelled' }),
      });
      if (r.ok) await reload();
    };

    return React.createElement('div', { style: { padding: 16 } },
      React.createElement('div', {
        style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 },
      },
        React.createElement('h2', { style: { margin: 0, fontSize: 18 } },
          FR ? 'Visites a venir (14j)' : 'Upcoming visits (14d)'
        ),
        React.createElement('button', {
          type: 'button',
          onClick: () => setShowForm(s => !s),
          style: {
            padding: '8px 14px', borderRadius: 8, border: 'none',
            background: '#0F172A', color: '#fff', fontSize: 13, fontWeight: 600, cursor: 'pointer',
          },
        }, showForm ? (FR ? 'Annuler' : 'Cancel') : (FR ? '+ Nouvelle visite' : '+ New visit'))
      ),

      showForm && React.createElement('form', {
        onSubmit: submit,
        style: {
          marginBottom: 16, padding: 14, background: '#f8fafc',
          borderRadius: 8, border: '1px solid #e2e8f0', display: 'grid', gap: 10,
        },
      },
        React.createElement('input', {
          type: 'datetime-local',
          value: form.scheduled_at,
          onChange: (e) => setForm(Object.assign({}, form, { scheduled_at: e.target.value })),
          required: true,
          style: { padding: 8, border: '1px solid #cbd5e1', borderRadius: 6 },
        }),
        React.createElement('input', {
          type: 'text', placeholder: FR ? 'Adresse' : 'Address',
          value: form.address,
          onChange: (e) => setForm(Object.assign({}, form, { address: e.target.value })),
          required: true,
          style: { padding: 8, border: '1px solid #cbd5e1', borderRadius: 6 },
        }),
        React.createElement('input', {
          type: 'text', placeholder: FR ? 'Nom du visiteur' : 'Visitor name',
          value: form.visitor_name,
          onChange: (e) => setForm(Object.assign({}, form, { visitor_name: e.target.value })),
          style: { padding: 8, border: '1px solid #cbd5e1', borderRadius: 6 },
        }),
        React.createElement('input', {
          type: 'email', placeholder: FR ? 'Email du visiteur' : 'Visitor email',
          value: form.visitor_email,
          onChange: (e) => setForm(Object.assign({}, form, { visitor_email: e.target.value })),
          style: { padding: 8, border: '1px solid #cbd5e1', borderRadius: 6 },
        }),
        React.createElement('textarea', {
          placeholder: FR ? 'Notes' : 'Notes',
          value: form.notes,
          onChange: (e) => setForm(Object.assign({}, form, { notes: e.target.value })),
          style: { padding: 8, border: '1px solid #cbd5e1', borderRadius: 6, minHeight: 60 },
        }),
        React.createElement('label', { style: { fontSize: 13, display: 'flex', gap: 6, alignItems: 'center' } },
          React.createElement('input', {
            type: 'checkbox', checked: form.push_to_google,
            onChange: (e) => setForm(Object.assign({}, form, { push_to_google: e.target.checked })),
          }),
          FR ? 'Synchroniser avec Google Calendar' : 'Sync with Google Calendar'
        ),
        React.createElement('button', {
          type: 'submit', disabled: saving,
          style: {
            padding: '10px 16px', borderRadius: 8, border: 'none',
            background: '#16a34a', color: '#fff', fontSize: 13, fontWeight: 600,
            cursor: saving ? 'not-allowed' : 'pointer', opacity: saving ? 0.6 : 1,
          },
        }, saving ? (FR ? 'Enregistrement…' : 'Saving…') : (FR ? 'Creer la visite' : 'Create visit'))
      ),

      error && React.createElement('div', {
        style: { padding: 10, background: '#fef2f2', color: '#dc2626', borderRadius: 6, marginBottom: 12, fontSize: 13 },
      }, error),

      loading
        ? React.createElement('div', { style: { color: '#64748b' } }, FR ? 'Chargement…' : 'Loading…')
        : visits.length === 0
          ? React.createElement('div', {
              style: { padding: 24, textAlign: 'center', color: '#64748b', background: '#f8fafc', borderRadius: 8 },
            }, FR ? 'Aucune visite a venir.' : 'No upcoming visits.')
          : React.createElement('div', { style: { display: 'grid', gap: 10 } },
              visits.map(v => React.createElement('div', {
                key: v.id,
                style: {
                  padding: 12, border: '1px solid #e2e8f0', borderRadius: 8,
                  background: '#fff', display: 'flex', justifyContent: 'space-between',
                  alignItems: 'flex-start', gap: 12,
                },
              },
                React.createElement('div', { style: { flex: 1 } },
                  React.createElement('div', {
                    style: { fontWeight: 600, fontSize: 14, color: '#0F172A' },
                  }, fmtWhen(v.scheduled_at, FR) + ' (' + v.duration_minutes + ' min)'),
                  React.createElement('div', {
                    style: { fontSize: 13, color: '#475569', marginTop: 2 },
                  }, v.address),
                  v.visitor_name && React.createElement('div', {
                    style: { fontSize: 12, color: '#64748b', marginTop: 2 },
                  }, (FR ? 'Visiteur : ' : 'Visitor: ') + v.visitor_name
                     + (v.visitor_email ? ' (' + v.visitor_email + ')' : '')),
                  React.createElement('div', {
                    style: { fontSize: 11, color: '#94a3b8', marginTop: 4 },
                  }, (FR ? 'Statut : ' : 'Status: ') + v.status
                     + ' · ' + (v.source === 'portal' ? (FR ? 'portail' : 'portal') : (FR ? 'courtier' : 'broker'))
                     + (v.google_event_id ? ' · Google' : ''))
                ),
                React.createElement('button', {
                  type: 'button',
                  onClick: () => cancel(v.id),
                  style: {
                    padding: '6px 10px', borderRadius: 6, border: '1px solid #fecaca',
                    background: '#fff', color: '#dc2626', fontSize: 12, cursor: 'pointer',
                  },
                }, FR ? 'Annuler' : 'Cancel')
              ))
            )
    );
  }

  window.BrokerAgendaPanel = BrokerAgendaPanel;
})();
