// Main wizard app
const { useState: uS, useEffect: uE, useMemo: uM, useCallback: uC } = React;

const STEPS = [
  { id: 'debut', label: 'Répartition', icon: <Icon.Phone />, comp: StepDebut },
  { id: 'loc', label: 'Localisation', icon: <Icon.MapPin />, comp: StepLocalisation },
  { id: 'team', label: 'Équipe', icon: <Icon.Users />, comp: StepEquipe },
  { id: 'patient', label: 'Patient', icon: <Icon.User />, comp: StepPatient },
  { id: 'eval', label: 'Évaluation', icon: <Icon.Stethoscope />, comp: StepEvaluation },
  { id: 'inj', label: 'Blessures', icon: <Icon.Bandage />, comp: StepBlessures },
  { id: 'sample', label: 'SAMPLE', icon: <Icon.FileText />, comp: StepSample },
  { id: 'care', label: 'Soins', icon: <Icon.Heart />, comp: StepSoins },
  { id: 'ev', label: 'Événement', icon: <Icon.AlertTriangle />, comp: StepEvenement },
  { id: 'transp', label: 'Transport', icon: <Icon.Truck />, comp: StepTransport },
  { id: 'recap', label: 'Récap & signer', icon: <Icon.Send />, comp: StepRecap },
];

const STORAGE_KEY = 'rapport-intervention-draft-v1';

function generateReportNumber(saison = 'ÉTÉ 2026') {
  const d = new Date();
  const yyyymmdd = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
  const seq = String(Math.floor(Math.random() * 900) + 100);
  return `${saison}-${yyyymmdd}-${seq}`;
}

function fmt(d, opts) { return d.toLocaleString('fr-CA', opts); }

function freshDraft() {
  return {
    saison: 'ÉTÉ 2026',
    reportNumber: generateReportNumber('ÉTÉ 2026'),
    date: new Date().toISOString().slice(0, 10),
    heure: new Date().toTimeString().slice(0, 5),
    team: ['', ''],
    patient: {},
    evaluation: { avpu: {} },
    injuries: [{}],
    sample: {},
    evenement: {},
    transport: {},
  };
}

function isStepComplete(step, data) {
  switch (step.id) {
    case 'debut': return !!(data.date && data.heure && data.repartiteur && data.appelant);
    case 'loc': return !!(data.endroit && data.repere && data.code);
    case 'team': return (data.team || []).filter(Boolean).length >= 1;
    case 'patient': return !!(data.patient?.prenom && data.patient?.nom);
    case 'eval': return !!(data.evaluation?.conscience);
    case 'inj': return (data.injuries || []).some(i => i.partie && i.type);
    case 'sample': return data.sample?.douleurNiveau != null;
    case 'care': return !!(data.soinsDetail);
    case 'ev': return !!(data.evenement?.cause);
    case 'transp': return !!(data.transport?.methode);
    case 'recap': return !!data.signature;
    default: return false;
  }
}

function App() {
  const [view, setView] = uS('wizard'); // 'wizard' | 'historique' | 'detail'
  const [detailReport, setDetailReport] = uS(null);
  const [stepIdx, setStepIdx] = uS(0);
  const [data, setData] = uS(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) return JSON.parse(stored);
    } catch (e) {}
    return freshDraft();
  });
  const [submitted, setSubmitted] = uS(false);
  const [savedAt, setSavedAt] = uS(null);

  uE(() => {
    if (submitted || view !== 'wizard') return;
    const t = setTimeout(() => {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
        setSavedAt(new Date());
      } catch (e) {}
    }, 400);
    return () => clearTimeout(t);
  }, [data, submitted, view]);

  const set = uC((key, val) => setData(prev => ({ ...prev, [key]: val })), []);

  const overall = uM(() => {
    const done = STEPS.filter(s => isStepComplete(s, data)).length;
    return Math.round((done / STEPS.length) * 100);
  }, [data]);

  const handleSubmit = () => {
    setSubmitted(true);
    localStorage.removeItem(STORAGE_KEY);
  };

  const handleNewReport = () => {
    setData(freshDraft());
    setStepIdx(0);
    setSubmitted(false);
    setView('wizard');
  };

  const openHistorique = () => { setView('historique'); setDetailReport(null); };
  const openReport = (r) => { setView('detail'); setDetailReport(r); };
  const backFromDetail = () => { setView('historique'); setDetailReport(null); };

  // ===== Sidebar (always present) =====
  const sidebarProps = {
    view, setView, openHistorique, handleNewReport,
    steps: STEPS, stepIdx, setStepIdx, data, overall, savedAt,
    submitted, detailReport,
  };

  // ===== Submitted screen =====
  if (submitted && view === 'wizard') {
    return (
      <div className="app">
        <Sidebar {...sidebarProps} />
        <div className="main">
          <div className="content">
            <StepSubmitted data={data} onNewReport={handleNewReport} />
          </div>
        </div>
      </div>
    );
  }

  // ===== Historique view =====
  if (view === 'historique') {
    return (
      <div className="app">
        <Sidebar {...sidebarProps} />
        <div className="main">
          <div className="topbar">
            <div className="topbar-left">
              <div className="topbar-title">Historique des rapports</div>
            </div>
            <div className="topbar-right">
              <button className="btn btn-ghost btn-sm" onClick={handleNewReport}>
                <Icon.Plus /> Nouveau rapport
              </button>
            </div>
          </div>
          <div className="content">
            <HistoriquePage onOpen={openReport} onNew={handleNewReport} />
          </div>
        </div>
      </div>
    );
  }

  // ===== Detail view =====
  if (view === 'detail' && detailReport) {
    return (
      <div className="app">
        <Sidebar {...sidebarProps} />
        <div className="main">
          <div className="topbar">
            <div className="topbar-left">
              <div className="step-counter mono">{detailReport.reportNumber.split('-').slice(1).join('-')}</div>
              <div className="topbar-title">{detailReport.patient.prenom} {detailReport.patient.nom}</div>
            </div>
          </div>
          <div className="content">
            <ReportDetail report={detailReport} onBack={backFromDetail} />
          </div>
        </div>
      </div>
    );
  }

  // ===== Wizard view =====
  const current = STEPS[stepIdx];
  const StepComp = current.comp;
  const isRecap = current.id === 'recap';

  return (
    <div className="app">
      <Sidebar {...sidebarProps} />

      <div className="main">
        <div className="topbar">
          <div className="topbar-left">
            <div className="step-counter">{String(stepIdx + 1).padStart(2, '0')} / {STEPS.length}</div>
            <div className="topbar-title">{current.label}</div>
          </div>
          <div className="topbar-right">
            <button className="btn btn-ghost btn-sm" onClick={openHistorique}>
              <Icon.FileText /> Historique
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => {
              if (confirm("Effacer ce brouillon et recommencer ?")) handleNewReport();
            }}>Nouveau</button>
          </div>
        </div>

        <div className="content">
          <StepComp data={data} set={set} jumpTo={(i) => setStepIdx(i)} onSubmit={handleSubmit} />
        </div>

        <div className="footer">
          <button
            className="btn"
            onClick={() => setStepIdx(Math.max(0, stepIdx - 1))}
            disabled={stepIdx === 0}
            style={stepIdx === 0 ? { opacity: 0.35, cursor: 'not-allowed' } : {}}
          >
            <Icon.ChevronLeft /> Précédent
          </button>

          <div className="footer-hint">
            {savedAt
              ? <>Brouillon sauvegardé · {fmt(savedAt, { hour: '2-digit', minute: '2-digit' })}</>
              : 'Brouillon non sauvegardé'}
          </div>

          {isRecap ? (
            <button
              className="btn btn-primary btn-lg"
              onClick={handleSubmit}
              disabled={!data.signature}
              style={!data.signature ? { opacity: 0.5, cursor: 'not-allowed' } : {}}
            >
              <Icon.Send /> Soumettre le rapport
            </button>
          ) : (
            <button className="btn btn-primary" onClick={() => setStepIdx(Math.min(STEPS.length - 1, stepIdx + 1))}>
              Suivant <Icon.ChevronRight />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

function Sidebar({ view, setView, openHistorique, handleNewReport, steps, stepIdx, setStepIdx, data, overall, savedAt, submitted, detailReport }) {
  return (
    <aside className="sidebar">
      <div className="brand">
        <div className="brand-mark">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M8 3l-6 18h20L14 3"/>
            <path d="M14 3l-3 9 3 6"/>
          </svg>
        </div>
        <div>
          <div className="brand-name">Patrouille Sutton</div>
          <div className="brand-sub">Plein Air · Été 2026</div>
        </div>
      </div>

      <div className="view-switch">
        <button
          className={view === 'wizard' && !submitted ? 'active' : ''}
          onClick={handleNewReport}
        >
          <Icon.Plus /> Nouveau
        </button>
        <button
          className={view === 'historique' || view === 'detail' ? 'active' : ''}
          onClick={openHistorique}
        >
          <Icon.FileText /> Historique
        </button>
      </div>

      {/* Wizard sidebar content */}
      {view === 'wizard' && !submitted && (
        <>
          <div className="report-meta">
            <div className="report-meta-label">N° de rapport en cours</div>
            <div className="report-meta-value">{data.reportNumber}</div>
          </div>

          <div>
            <div className="nav-section-label">Étapes</div>
            <div className="nav-list">
              {steps.map((s, i) => {
                const done = isStepComplete(s, data);
                const active = i === stepIdx;
                return (
                  <button
                    key={s.id}
                    className={`nav-item ${active ? 'active' : ''} ${done && !active ? 'done' : ''}`}
                    onClick={() => setStepIdx(i)}
                  >
                    <span className="nav-num">{done && !active ? <Icon.Check style={{ width: 12, height: 12 }} /> : i + 1}</span>
                    <span>{s.label}</span>
                  </button>
                );
              })}
            </div>
          </div>

          <div className="progress-overall">
            <div className="progress-row">
              <span className="progress-label">Progression</span>
              <span className="progress-value">{overall}%</span>
            </div>
            <div className="progress-bar">
              <div className="progress-fill" style={{ width: `${overall}%` }}></div>
            </div>
            {savedAt && (
              <div className="draft-saved">
                <span className="dot"></span> Brouillon sauvegardé · {fmt(savedAt, { hour: '2-digit', minute: '2-digit' })}
              </div>
            )}
          </div>
        </>
      )}

      {/* Historique sidebar content */}
      {(view === 'historique' || view === 'detail') && (
        <>
          <div className="report-meta">
            <div className="report-meta-label">Total rapports · saison</div>
            <div className="report-meta-value">{window.MOCK_REPORTS.length}</div>
          </div>

          <div>
            <div className="nav-section-label">Vues rapides</div>
            <div className="nav-list">
              <button className="nav-item active">
                <span className="nav-num"><Icon.FileText style={{ width: 12, height: 12 }} /></span>
                <span>Tous les rapports</span>
              </button>
              <button className="nav-item" style={{ opacity: 0.5 }} disabled>
                <span className="nav-num"><Icon.AlertTriangle style={{ width: 12, height: 12 }} /></span>
                <span>Codes rouges</span>
              </button>
              <button className="nav-item" style={{ opacity: 0.5 }} disabled>
                <span className="nav-num"><Icon.Phone style={{ width: 12, height: 12 }} /></span>
                <span>Appels 911</span>
              </button>
              <button className="nav-item" style={{ opacity: 0.5 }} disabled>
                <span className="nav-num"><Icon.User style={{ width: 12, height: 12 }} /></span>
                <span>Mes rapports</span>
              </button>
            </div>
          </div>

          <div className="progress-overall">
            <div style={{ fontSize: 11.5, color: 'rgba(231,234,232,0.5)', marginBottom: 4 }}>
              Connecté à
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span className="dot" style={{ width: 6, height: 6, borderRadius: '50%', background: '#4A8A66', boxShadow: '0 0 6px #4A8A66' }}></span>
              <span style={{ fontFamily: 'Geist Mono', fontSize: 11.5, color: '#E7EAE8' }}>Google Sheet · live</span>
            </div>
          </div>
        </>
      )}
    </aside>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
