// AAP — Issue Tracker (drawer + form + flag button)
const { useState: useState_i, useEffect: useEffect_i, useRef: useRef_i } = React;
const Icon_i = window.AAP_Icon;

const SEVERITIES = [
  { id: 'critical', label: 'Critique', desc: 'Bloquant / erreur factuelle grave' },
  { id: 'warning', label: 'Modéré', desc: 'Imprécision, ton inadapté' },
  { id: 'minor', label: 'Mineur', desc: 'Suggestion d\'amélioration' },
];
const CATEGORIES = [
  'Données incorrectes',
  'Hallucination',
  'Ton / formulation',
  'Calcul erroné',
  'Outil mal utilisé',
  'Compliance / RGPD',
  'UX / lisibilité',
  'Autre',
];

const STORAGE_KEY = 'aap_issues_v1';

function loadIssues() {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) return JSON.parse(raw);
  } catch (e) {}
  // Seed with one demo issue so the panel isn't empty on first load
  return [
    {
      id: 'demo-1',
      title: 'Plafond RC Pro mal indiqué pour 80 sal.',
      desc: 'AAP a annoncé 8 M€ alors que la grille actuarielle plafonne à 6 M€ pour ce profil. Vérifier la table v4.2.',
      quote: 'Notre avantage clé : cyber natif et plafond supérieur à prix égal…',
      severity: 'warning',
      category: 'Données incorrectes',
      createdAt: Date.now() - 1000 * 60 * 47,
      resolved: false,
    },
  ];
}

function saveIssues(issues) {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(issues)); } catch (e) {}
}

function relativeTime(ts) {
  const diff = (Date.now() - ts) / 1000;
  if (diff < 60) return 'à l\'instant';
  if (diff < 3600) return `il y a ${Math.floor(diff/60)} min`;
  if (diff < 86400) return `il y a ${Math.floor(diff/3600)} h`;
  return `il y a ${Math.floor(diff/86400)} j`;
}

// ============ Issue Form ============
function IssueForm({ initial, onSave, onCancel }) {
  const [title, setTitle] = useState_i(initial?.title || '');
  const [desc, setDesc] = useState_i(initial?.desc || '');
  const [quote, setQuote] = useState_i(initial?.quote || '');
  const [severity, setSeverity] = useState_i(initial?.severity || 'warning');
  const [category, setCategory] = useState_i(initial?.category || CATEGORIES[0]);

  const canSave = title.trim().length > 0;

  const submit = () => {
    if (!canSave) return;
    onSave({
      ...initial,
      title: title.trim(),
      desc: desc.trim(),
      quote: quote.trim(),
      severity,
      category,
      createdAt: initial?.createdAt || Date.now(),
      updatedAt: initial ? Date.now() : undefined,
    });
  };

  return (
    <div className="issue-form">
      <h3 className="issue-form-title">
        <Icon_i.Sparkle s={14}/>
        {initial ? 'Modifier l\'anomalie' : 'Nouvelle anomalie'}
      </h3>
      <div className="field">
        <label className="field-label">Sévérité</label>
        <div className="severity-picker">
          {SEVERITIES.map(s => (
            <button
              key={s.id}
              type="button"
              className={"sev-pick " + s.id + (severity === s.id ? ' active' : '')}
              onClick={() => setSeverity(s.id)}
              title={s.desc}
            >
              <span className="pulse-dot"/> {s.label}
            </button>
          ))}
        </div>
      </div>
      <div className="field">
        <label className="field-label">Catégorie</label>
        <select className="field-select" value={category} onChange={e => setCategory(e.target.value)}>
          {CATEGORIES.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
      </div>
      <div className="field">
        <label className="field-label">Titre *</label>
        <input
          className="field-input"
          value={title}
          onChange={e => setTitle(e.target.value)}
          placeholder="Ex : AAP cite un mauvais plafond RC Pro"
          autoFocus
        />
      </div>
      <div className="field">
        <label className="field-label">Description détaillée</label>
        <textarea
          className="field-textarea"
          value={desc}
          onChange={e => setDesc(e.target.value)}
          placeholder="Décrivez le problème observé et le comportement attendu…"
        />
      </div>
      <div className="field">
        <label className="field-label">Extrait de la réponse AAP (optionnel)</label>
        <textarea
          className="field-textarea"
          value={quote}
          onChange={e => setQuote(e.target.value)}
          placeholder="Collez ici le passage problématique pour le contexte"
          style={{minHeight: 50}}
        />
      </div>
      <div className="form-actions">
        <button className="btn-secondary" onClick={onCancel}>Annuler</button>
        <button className="btn-primary" disabled={!canSave} onClick={submit}>
          {initial ? 'Enregistrer' : 'Créer l\'anomalie'}
        </button>
      </div>
    </div>
  );
}

// ============ Issue Card ============
function IssueCard({ issue, onEdit, onDelete }) {
  const sev = SEVERITIES.find(s => s.id === issue.severity) || SEVERITIES[1];
  return (
    <div className={"issue-card severity-" + issue.severity + (issue.resolved ? ' resolved' : '')}>
      <div className="issue-meta-row">
        <span className={"severity-chip " + issue.severity}>
          <span className="pulse-dot"/> {sev.label}
        </span>
        <span className="cat-chip">{issue.category}</span>
        <span className="issue-time">{relativeTime(issue.createdAt)}</span>
      </div>
      <div className="issue-title-text">{issue.title}</div>
      {issue.desc && <div className="issue-desc">{issue.desc}</div>}
      {issue.quote && <div className="issue-quote">« {issue.quote} »</div>}
      <div className="issue-actions">
        <button className="iact" onClick={onEdit} title="Modifier">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/></svg>
          Modifier
        </button>
        <button className="iact delete" onClick={onDelete} title="Supprimer">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/></svg>
          Supprimer
        </button>
      </div>
    </div>
  );
}

// ============ Issues Drawer ============
function IssuesDrawer({ open, onClose, issues, setIssues, draftFromMessage, clearDraft,
                        sessionUuid, testerName, testerEmail }) {
  const [editing, setEditing] = useState_i(null); // issue or { _new: true, ...prefill }

  useEffect_i(() => {
    if (draftFromMessage && open) {
      setEditing({ _new: true, quote: draftFromMessage, severity: 'warning', category: CATEGORIES[0] });
    }
  }, [draftFromMessage, open]);

  const counts = {
    total: issues.length,
    critical: issues.filter(i => i.severity === 'critical').length,
    warning: issues.filter(i => i.severity === 'warning').length,
    minor: issues.filter(i => i.severity === 'minor').length,
  };

  // Sync issue vers le tracking server (fire-and-forget)
  const trackIssue = (issue) => {
    fetch('/track', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        event:           'issue',
        session_uuid:    sessionUuid || '',
        tester_name:     testerName || 'Jeremy',
        tester_email:    testerEmail || '',
        issue_client_id: issue.id || '',
        title:           issue.title || '',
        description:     issue.desc || '',
        quote_text:      issue.quote || '',
        severity:        issue.severity || 'warning',
        category:        issue.category || 'Autre',
      }),
    }).catch(() => {});
  };

  const handleSave = (data) => {
    if (data.id) {
      setIssues(issues.map(i => i.id === data.id ? { ...i, ...data } : i));
      // Mise à jour : pas de re-tracking pour les modifications
    } else {
      const nu = { ...data, id: 'i_' + Date.now() };
      setIssues([nu, ...issues]);
      // Nouvelle issue → tracker en DB
      trackIssue(nu);
    }
    setEditing(null);
    if (clearDraft) clearDraft();
  };

  const handleCancel = () => {
    setEditing(null);
    if (clearDraft) clearDraft();
  };

  const handleDelete = (id) => {
    setIssues(issues.filter(i => i.id !== id));
  };

  return (
    <>
      <div className={"issues-overlay" + (open ? ' open' : '')} onClick={onClose}/>
      <aside className={"issues-drawer" + (open ? ' open' : '')} aria-hidden={!open}>
        <div className="issues-header">
          <div className="issues-header-top">
            <div>
              <h2 className="issues-title">Banc <em>de test</em></h2>
              <div className="issues-subtitle">Anomalies détectées sur les réponses d'AAP</div>
            </div>
            <button className="issues-close" onClick={onClose} title="Fermer">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
            </button>
          </div>
        </div>

        <div className="issues-stats">
          <div className="istat">
            <div className="v">{counts.total}</div>
            <div className="l">Total</div>
          </div>
          <div className="istat">
            <div className="v crit">{counts.critical}</div>
            <div className="l">Critiques</div>
          </div>
          <div className="istat">
            <div className="v warn">{counts.warning}</div>
            <div className="l">Modérés</div>
          </div>
          <div className="istat">
            <div className="v minor">{counts.minor}</div>
            <div className="l">Mineurs</div>
          </div>
        </div>

        <div className="issues-list">
          {editing && (
            <IssueForm
              initial={editing._new ? editing : editing}
              onSave={handleSave}
              onCancel={handleCancel}
            />
          )}

          {!editing && issues.length === 0 && (
            <div className="issues-empty">
              <div className="ico">
                <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><path d="M4 4l16 16M4 20L20 4"/><circle cx="12" cy="12" r="9"/></svg>
              </div>
              <h3>Aucune anomalie</h3>
              <p>Cliquez sur le drapeau d'un message AAP, ou utilisez le bouton ci-dessous pour signaler une erreur.</p>
            </div>
          )}

          {!editing && issues.map(issue => (
            <IssueCard
              key={issue.id}
              issue={issue}
              onEdit={() => setEditing(issue)}
              onDelete={() => handleDelete(issue.id)}
            />
          ))}
        </div>

        {!editing && (
          <div className="issue-add-fab-wrap">
            <button className="issue-add-fab" onClick={() => setEditing({ _new: true })}>
              <Icon_i.Plus s={14}/>
              Signaler une anomalie
            </button>
          </div>
        )}
      </aside>
    </>
  );
}

// ============ Flag button (for AI messages) ============
function FlagButton({ onFlag, flagged }) {
  return (
    <button
      className={"flag-btn" + (flagged ? ' flagged' : '')}
      onClick={onFlag}
      title="Signaler une anomalie sur cette réponse"
    >
      <svg width="11" height="11" viewBox="0 0 24 24" fill={flagged ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/>
        <line x1="4" y1="22" x2="4" y2="15"/>
      </svg>
      {flagged ? 'Anomalie signalée' : 'Signaler une anomalie'}
    </button>
  );
}

Object.assign(window, { IssuesDrawer, FlagButton, loadIssues, saveIssues });
