/* global React */
// Dossiers — Kanban + Table view + Map view

function DossiersPage({ onOpenDossier }) {
  const [view, setView] = useState('kanban');
  const [newOppOpen, setNewOppOpen] = useState(false);
  const [syncState, setSyncState] = useState({ loading: false, message: null });
  const doSyncOdoo = async () => {
    setSyncState({ loading: true, message: null });
    const res = await window.triggerOdooSync();
    const msg = res?.ok ? (res.created != null ? `✓ ${res.created} créés · ${res.updated || 0} maj` : '✓ sync OK') : `⚠ ${res?.error || 'échec'}`;
    setSyncState({ loading: false, message: msg });
    // Re-hydrate dossiers après sync
    if (res?.ok && window.AE_API?.hydrate) setTimeout(() => window.AE_API.hydrate(), 500);
    setTimeout(() => setSyncState({ loading: false, message: null }), 5000);
  };
  return (
    <div style={{ padding: '16px 24px 80px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <h1 style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>Cycle de vie des dossiers</h1>
        <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', padding: '2px 8px', border: '1px solid var(--line)', borderRadius: 999 }}>
          {DOSSIERS.length} dossiers · {fmtMWh(DOSSIERS.reduce((s, d) => s + d.cumac, 0))}
        </span>
        <div style={{ flex: 1 }} />
        <div style={{ display: 'flex', gap: 2, padding: 2, background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 6 }}>
          {[
            { k: 'kanban', l: 'Kanban', i: <Icon.kanban /> },
            { k: 'table',  l: 'Tableau', i: <Icon.chart /> },
            { k: 'map',    l: 'Carte', i: <Icon.map /> },
          ].map(o => (
            <button key={o.k} onClick={() => setView(o.k)} style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '4px 10px', fontSize: 12, fontWeight: 500,
              background: view === o.k ? 'var(--paper)' : 'transparent',
              color: view === o.k ? 'var(--ink)' : 'var(--ink-3)',
              border: view === o.k ? '1px solid var(--line)' : '1px solid transparent',
              borderRadius: 4,
            }}>{o.i} {o.l}</button>
          ))}
        </div>
        <Btn variant="outline" size="sm" onClick={doSyncOdoo} disabled={syncState.loading}>
          {syncState.loading ? '⏳ Sync Odoo…' : syncState.message || '⟳ Sync Odoo'}
        </Btn>
        <Btn variant="outline" size="sm" icon={<Icon.filter />}>Filtres</Btn>
        <Btn variant="signal" size="sm" icon={<Icon.plus />} onClick={() => setNewOppOpen(true)}>Nouveau</Btn>
      </div>

      {newOppOpen && window.CreateOpportunityModal && (
        <window.CreateOpportunityModal
          onClose={() => setNewOppOpen(false)}
          onCreated={(opp) => { if (window.AE_API?.hydrate) window.AE_API.hydrate(); }}
        />
      )}

      {DOSSIERS.length === 0 ? (
        window.EmptyState ? (
          <window.EmptyState
            icon="📁"
            title="Aucun dossier CEE"
            sub="Vos dossiers CEE (drafts, validés, déposés) apparaîtront ici. Synchronisez avec Odoo ou créez un nouveau dossier pour démarrer."
            cta={{ label: '+ Nouveau dossier', onClick: () => setNewOppOpen(true) }}
            secondaryCta={{ label: '⟳ Sync Odoo', onClick: doSyncOdoo }}
          />
        ) : null
      ) : (
        <>
          {view === 'kanban' && <Kanban onOpenDossier={onOpenDossier} />}
          {view === 'table' && <DossierTable onOpenDossier={onOpenDossier} />}
          {view === 'map' && <DossierMap />}
        </>
      )}
    </div>
  );
}

function Kanban({ onOpenDossier }) {
  const cols = STAGES.map(s => ({ ...s, items: DOSSIERS.filter(d => d.stage === s.key) }));
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${STAGES.length}, minmax(260px, 1fr))`, gap: 10, overflowX: 'auto', paddingBottom: 20 }}>
      {cols.map(col => {
        const totalCumac = col.items.reduce((s, d) => s + d.cumac, 0);
        return (
          <div key={col.key} style={{
            display: 'flex', flexDirection: 'column', gap: 8,
            background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 8,
            padding: 10,
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 2px 8px', borderBottom: '1px solid var(--hairline)' }}>
              <Dot tone={col.tone} size={6} />
              <span style={{ fontSize: 12, fontWeight: 600 }}>{col.label}</span>
              <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)', marginLeft: 'auto' }}>{col.items.length}</span>
            </div>
            <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)', padding: '0 2px', marginTop: -4 }}>
              {col.sub} · {fmtMWh(totalCumac)}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 640, overflowY: 'auto' }}>
              {col.items.slice(0, 6).map((d, i) => (
                <KanbanCard key={d.ref} d={d} delay={i * 40} onClick={() => onOpenDossier(d)} />
              ))}
              {col.items.length > 6 && (
                <button style={{ fontSize: 11, color: 'var(--ink-3)', padding: 8, textAlign: 'center' }}>
                  +{col.items.length - 6} autres
                </button>
              )}
              {col.items.length === 0 && (
                <div style={{ padding: 16, fontSize: 11, color: 'var(--ink-4)', textAlign: 'center', fontStyle: 'italic' }}>aucun dossier</div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function KanbanCard({ d, onClick, delay = 0 }) {
  const riskTone = d.risk >= 80 ? 'signal' : d.risk >= 60 ? 'amber' : 'rouge';
  return (
    <button
      onClick={onClick}
      className="fade-up"
      style={{
        background: 'var(--paper)',
        border: '1px solid var(--line)', borderRadius: 6,
        padding: 10, textAlign: 'left',
        display: 'flex', flexDirection: 'column', gap: 6,
        animationDelay: `${delay}ms`,
        transition: 'all 150ms',
      }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = 'var(--shadow-2)'; e.currentTarget.style.borderColor = 'var(--line-2)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.transform = 'translateY(0)'; }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Sigil seed={d.ref} size={16} />
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', fontWeight: 500 }}>{d.ref}</span>
        <span style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--ink-4)' }}>J+{d.ageDays}</span>
      </div>
      <div style={{ fontSize: 12, fontWeight: 600, lineHeight: 1.3 }}>{d.client}</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <span className="mono" style={{ fontSize: 10, padding: '1px 5px', background: 'var(--paper-2)', border: '1px solid var(--line)', borderRadius: 3, color: 'var(--ink-2)' }}>{d.fost}</span>
        <span className="mono" style={{ fontSize: 10, color: 'var(--ink-4)' }}>· {d.zone} · {d.city}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
        <div style={{ flex: 1 }}>
          <div className="num" style={{ fontSize: 13, fontWeight: 600 }}>{fmtMWh(d.cumac)}</div>
          <div className="num" style={{ fontSize: 10, color: 'var(--ink-4)' }}>{fmtEur(d.amount)}</div>
        </div>
        <RiskRing value={d.risk} tone={riskTone} />
      </div>
      {/* Ownership + pieces progress */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, paddingTop: 6, borderTop: '1px solid var(--hairline)', marginTop: 2 }}>
        <div style={{ width: 18, height: 18, borderRadius: '50%', background: 'var(--ink)', color: 'var(--paper)', display: 'grid', placeItems: 'center', fontSize: 8, fontWeight: 600 }}>
          {d.owner.split(' ').map(s => s[0]).join('')}
        </div>
        <div style={{ flex: 1, display: 'flex', gap: 1 }}>
          {Array.from({ length: d.pieces.total }).map((_, i) => (
            <div key={i} style={{ flex: 1, height: 3, borderRadius: 1, background: i < d.pieces.ok ? 'var(--signal)' : 'var(--paper-3)' }} />
          ))}
        </div>
        <span className="mono" style={{ fontSize: 9, color: 'var(--ink-4)' }}>{d.pieces.ok}/{d.pieces.total}</span>
      </div>
    </button>
  );
}

function RiskRing({ value, tone, size = 28 }) {
  const r = (size - 4) / 2;
  const c = 2 * Math.PI * r;
  const offset = c - (value / 100) * c;
  const color = tone === 'signal' ? 'var(--signal-deep)' : tone === 'amber' ? 'var(--amber)' : 'var(--rouge)';
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--paper-3)" strokeWidth="2" />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth="2"
          strokeDasharray={c} strokeDashoffset={offset}
          strokeLinecap="round"
          transform={`rotate(-90 ${size/2} ${size/2})`}
          style={{ transition: 'stroke-dashoffset 400ms' }} />
      </svg>
      <span className="num" style={{
        position: 'absolute', inset: 0, display: 'grid', placeItems: 'center',
        fontSize: 9, fontWeight: 600, color: color,
      }}>{value}</span>
    </div>
  );
}

function DossierTable({ onOpenDossier }) {
  return (
    <div style={{ border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper-2)', overflow: 'hidden' }}>
      <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12 }}>
        <thead>
          <tr style={{ background: 'var(--paper-2)', borderBottom: '1px solid var(--line)' }}>
            {['Réf.', 'Client', 'FOST', 'Zone', 'Statut', 'Cumac', 'Prime', 'Score PNCEE', 'Propriétaire', 'Âge'].map(h => (
              <th key={h} style={{ padding: '10px 12px', textAlign: 'left', fontSize: 10, fontWeight: 600, color: 'var(--ink-4)', textTransform: 'uppercase', letterSpacing: 0.6 }}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {DOSSIERS.slice(0, 20).map((d, i) => {
            const stage = STAGES.find(s => s.key === d.stage);
            const riskTone = d.risk >= 80 ? 'signal' : d.risk >= 60 ? 'amber' : 'rouge';
            return (
              <tr key={d.ref} onClick={() => onOpenDossier(d)}
                style={{ borderBottom: '1px solid var(--hairline)', cursor: 'pointer', background: i % 2 ? 'var(--paper)' : 'transparent' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--signal-tint)'}
                onMouseLeave={e => e.currentTarget.style.background = i % 2 ? 'var(--paper)' : 'transparent'}
              >
                <td style={{ padding: '9px 12px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Sigil seed={d.ref} size={16} />
                    <span className="mono" style={{ fontSize: 11, fontWeight: 500 }}>{d.ref}</span>
                  </div>
                </td>
                <td style={{ padding: '9px 12px', fontWeight: 500 }}>{d.client}</td>
                <td style={{ padding: '9px 12px' }}><span className="mono" style={{ fontSize: 10, padding: '1px 5px', background: 'var(--paper-3)', borderRadius: 3 }}>{d.fost}</span></td>
                <td style={{ padding: '9px 12px' }} className="mono">{d.zone}</td>
                <td style={{ padding: '9px 12px' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                    <Dot tone={stage.tone} size={5} />
                    <span style={{ fontSize: 11 }}>{stage.label}</span>
                  </span>
                </td>
                <td style={{ padding: '9px 12px', textAlign: 'right' }} className="num">{fmtMWh(d.cumac)}</td>
                <td style={{ padding: '9px 12px', textAlign: 'right' }} className="num">{fmtEur(d.amount)}</td>
                <td style={{ padding: '9px 12px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: 36, height: 4, background: 'var(--paper-3)', borderRadius: 2, overflow: 'hidden' }}>
                      <div style={{ height: '100%', width: `${d.risk}%`, background: riskTone === 'signal' ? 'var(--signal-deep)' : riskTone === 'amber' ? 'var(--amber)' : 'var(--rouge)' }} />
                    </div>
                    <span className="num" style={{ fontSize: 10, color: 'var(--ink-3)', width: 22 }}>{d.risk}</span>
                  </div>
                </td>
                <td style={{ padding: '9px 12px' }}>{d.owner}</td>
                <td style={{ padding: '9px 12px' }} className="mono">J+{d.ageDays}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <div style={{ padding: '10px 14px', borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', fontSize: 11, color: 'var(--ink-4)' }}>
        <span>20 de {DOSSIERS.length}</span>
        <span style={{ flex: 1 }} />
        <span className="mono">pagination virtuelle active</span>
      </div>
    </div>
  );
}

function DossierMap() {
  // Simple France SVG silhouette w/ city dots
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16 }}>
      <div style={{ border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper-2)', padding: 20, position: 'relative', minHeight: 600 }}>
        <svg viewBox="0 0 400 450" style={{ width: '100%', height: 560 }}>
          <defs>
            <pattern id="mapgrid" width="20" height="20" patternUnits="userSpaceOnUse">
              <path d="M 20 0 L 0 0 0 20" fill="none" stroke="var(--hairline)" strokeWidth="1"/>
            </pattern>
          </defs>
          <rect width="400" height="450" fill="url(#mapgrid)" />
          {/* France rough path */}
          <path d="M160 60 L210 52 L240 68 L270 90 L290 130 L320 150 L330 180 L340 220 L330 260 L320 290 L290 310 L270 340 L250 380 L220 400 L180 395 L150 380 L130 350 L110 310 L90 270 L75 220 L80 180 L90 140 L110 100 L140 75 Z"
            fill="var(--paper-3)" stroke="var(--line-2)" strokeWidth="1" />
          {/* Cities mapped roughly */}
          {[
            { city: 'Lille', x: 210, y: 80 },
            { city: 'Strasbourg', x: 310, y: 130 },
            { city: 'Lyon', x: 260, y: 240 },
            { city: 'Nantes', x: 130, y: 220 },
            { city: 'Bordeaux', x: 150, y: 310 },
            { city: 'Toulouse', x: 190, y: 360 },
            { city: 'Marseille', x: 270, y: 370 },
            { city: 'Nice', x: 310, y: 350 },
          ].map((p) => {
            const n = DOSSIERS.filter(d => d.city === p.city).length;
            const r = 4 + n * 0.8;
            return (
              <g key={p.city}>
                <circle cx={p.x} cy={p.y} r={r + 4} fill="var(--signal)" opacity="0.12" />
                <circle cx={p.x} cy={p.y} r={r} fill="var(--signal)" opacity="0.6" stroke="var(--signal-deep)" strokeWidth="1" />
                <text x={p.x + r + 4} y={p.y + 3} fontSize="9" fill="var(--ink-2)" fontFamily="General Sans">{p.city} · {n}</text>
              </g>
            );
          })}
        </svg>
        <div style={{ position: 'absolute', top: 14, left: 14, fontSize: 11, color: 'var(--ink-4)' }} className="mono">géoloc chantiers · cluster = volume</div>
      </div>
      <div style={{ border: '1px solid var(--line)', borderRadius: 8, background: 'var(--paper-2)', padding: 16, display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Concentration par zone climatique</div>
        {['H1a','H1b','H1c','H2a','H2c','H3'].map(z => {
          const n = DOSSIERS.filter(d => d.zone === z).length;
          const cumac = DOSSIERS.filter(d => d.zone === z).reduce((s, d) => s + d.cumac, 0);
          return (
            <div key={z} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span className="mono" style={{ fontSize: 11, width: 30 }}>{z}</span>
              <div style={{ flex: 1, height: 6, background: 'var(--paper-3)', borderRadius: 3 }}>
                <div style={{ height: '100%', width: `${(n / DOSSIERS.length) * 100}%`, background: 'var(--signal)', borderRadius: 3 }} />
              </div>
              <span className="num" style={{ fontSize: 11, width: 22, textAlign: 'right' }}>{n}</span>
              <span className="num" style={{ fontSize: 10, color: 'var(--ink-4)', width: 60, textAlign: 'right' }}>{fmtMWh(cumac)}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { DossiersPage });
