// ============================================================================
//  detail.jsx — Pane détails d'une entrée mot de passe.
//  TOTP calculés dynamiquement via CPCrypto.computeTotp (RFC 6238).
// ============================================================================

const { useState, useEffect, useRef } = React;

// useCopy + Field exportés globaux (réutilisés par wifi.jsx).
const useCopy = () => {
  const [copied, setCopied] = useState(null);
  const copy = (id, text) => {
    try { navigator.clipboard.writeText(text); } catch (e) {}
    setCopied(id);
    setTimeout(() => setCopied(null), 1500);
  };
  return [copied, copy];
};
window.useCopy = useCopy;

const TotpRing = ({ remaining, period, size = 28 }) => {
  const r = (size - 4) / 2;
  const c = 2 * Math.PI * r;
  const pct = remaining / period;
  const danger = remaining <= 5;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} className="cp-totp-ring">
      <circle cx={size/2} cy={size/2} r={r} stroke="rgba(255,255,255,.08)" strokeWidth="2" fill="none"/>
      <circle
        cx={size/2} cy={size/2} r={r}
        stroke={danger ? '#EF4444' : 'url(#tg)'}
        strokeWidth="2" fill="none"
        strokeDasharray={c}
        strokeDashoffset={c * (1 - pct)}
        strokeLinecap="round"
        transform={`rotate(-90 ${size/2} ${size/2})`}
        style={{ transition: 'stroke-dashoffset 1s linear, stroke .3s' }}
      />
      <defs>
        <linearGradient id="tg" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0" stopColor="#6366F1"/>
          <stop offset="1" stopColor="#EC4899"/>
        </linearGradient>
      </defs>
      <text x={size/2} y={size/2 + 3} textAnchor="middle" fontSize="9" fontWeight="600" fill="currentColor">{remaining}</text>
    </svg>
  );
};

const AccountBlock = ({ account, copied, onCopy, isPrimary }) => {
  const [show, setShow] = useState(false);
  return (
    <div className="cp-block">
      <div className="cp-block-head">
        <span className="cp-block-label">{account.label}</span>
        {isPrimary && <span className="cp-block-tag">principal</span>}
        <span className="cp-block-spacer" />
      </div>

      <Field
        label="Nom d'utilisateur"
        value={account.username}
        copied={copied === `u-${account.id}`}
        onCopy={() => onCopy(`u-${account.id}`, account.username)}
      />

      <Field
        label="Mot de passe"
        value={show ? account.password : '••••••••••••••••'}
        mono
        copied={copied === `p-${account.id}`}
        onCopy={() => onCopy(`p-${account.id}`, account.password)}
        right={
          <button className="cp-field-eye" onClick={() => setShow(!show)} title={show ? 'Masquer' : 'Afficher'}>
            <Icon name={show ? 'eye-off' : 'eye'} size={14} />
          </button>
        }
      />

      {account.created && <div className="cp-block-meta">Créé le {account.created}</div>}
    </div>
  );
};

// TOTP : calcul live via WebCrypto. Re-render chaque seconde.
const TotpBlock = ({ totp, copied, onCopy }) => {
  const [code, setCode] = useState('------');
  const [remaining, setRemaining] = useState(totp.period || 30);
  const period = totp.period || 30;

  useEffect(() => {
    let cancelled = false;
    const recompute = async () => {
      try {
        const c = await CPCrypto.computeTotp(totp.secret, period);
        if (!cancelled) {
          setCode(c);
          setRemaining(CPCrypto.totpRemaining(period));
        }
      } catch {
        if (!cancelled) setCode('------');
      }
    };
    recompute();
    const id = setInterval(recompute, 1000);
    return () => { cancelled = true; clearInterval(id); };
  }, [totp.secret, period]);

  const fmt = code && code.length === 6 ? code.slice(0, 3) + ' ' + code.slice(3) : code;

  return (
    <div className="cp-block cp-block-totp">
      <div className="cp-block-head">
        <span className="cp-block-label">{totp.label}</span>
        <span className="cp-block-spacer" />
      </div>
      <div className="cp-totp-row">
        <div className="cp-totp-code">
          <span>{fmt.slice(0, 3)}</span>
          <span className="cp-totp-dot" />
          <span>{fmt.slice(4)}</span>
        </div>
        <div className="cp-totp-right">
          <TotpRing remaining={remaining} period={period} />
          <button
            className={`cp-copy-btn ${copied === `t-${totp.id}` ? 'is-copied' : ''}`}
            onClick={() => onCopy(`t-${totp.id}`, code.replace(/\s/g, ''))}
          >
            <Icon name={copied === `t-${totp.id}` ? 'check' : 'copy'} size={13} />
            <span>{copied === `t-${totp.id}` ? 'Copié' : 'Copier'}</span>
          </button>
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, value, mono, copied, onCopy, right }) => (
  <div className="cp-field">
    <div className="cp-field-label">{label}</div>
    <div className="cp-field-row">
      <span className={`cp-field-val ${mono ? 'is-mono' : ''}`}>{value}</span>
      <div className="cp-field-actions">
        {right}
        <button
          className={`cp-field-copy ${copied ? 'is-copied' : ''}`}
          onClick={onCopy}
          title={copied ? 'Copié' : 'Copier'}
        >
          <Icon name={copied ? 'check' : 'copy'} size={13} />
        </button>
      </div>
    </div>
  </div>
);

const SecurityCard = ({ entry }) => {
  const score = entry.strength === 'strong' ? 92 : entry.strength === 'medium' ? 58 : 24;
  const colors = { strong: '#10B981', medium: '#F59E0B', weak: '#EF4444' };
  const labels = {
    strong: 'Mot de passe robuste',
    medium: 'Force moyenne',
    weak:   'Mot de passe faible',
  };
  const sub = {
    strong: 'Long, unique, difficile à deviner.',
    medium: 'Pourrait être plus long ou plus aléatoire.',
    weak:   'Trop court ou réutilisé. Régénérez-le.',
  };
  return (
    <div className="cp-sec">
      <div className="cp-sec-head">
        <Icon name="shield-check" size={14} color={colors[entry.strength] || '#888'} />
        <span>Sécurité</span>
      </div>
      <div className="cp-sec-body">
        <div className="cp-sec-meter">
          <div className="cp-sec-meter-fill" style={{ width: score + '%', background: colors[entry.strength] || '#888' }} />
        </div>
        <div className="cp-sec-text">
          <div className="cp-sec-title" style={{ color: colors[entry.strength] || 'inherit' }}>
            {labels[entry.strength] || 'Force inconnue'}
          </div>
          <div className="cp-sec-sub">{sub[entry.strength] || ''}</div>
        </div>
      </div>
    </div>
  );
};

// Petit menu déroulant pour le bouton "..." du hero.
const MoreMenu = ({ favorite, onToggleFavorite, onDelete }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [open]);

  return (
    <div className="cp-more-wrap" ref={ref}>
      <button className="cp-btn cp-btn-ghost-icon" onClick={() => setOpen(o => !o)} title="Plus">
        <Icon name="more" size={14} />
      </button>
      {open && (
        <div className="cp-more-menu">
          <button onClick={() => { onToggleFavorite(); setOpen(false); }}>
            <Icon name="star" size={13} />
            <span>{favorite ? 'Retirer des favoris' : 'Ajouter aux favoris'}</span>
          </button>
          <button className="cp-more-danger" onClick={() => {
            if (confirm('Supprimer définitivement cette entrée ?')) onDelete();
            setOpen(false);
          }}>
            <Icon name="trash" size={13} />
            <span>Supprimer</span>
          </button>
        </div>
      )}
    </div>
  );
};

const Detail = ({ entry, onEncryptionInfo, onEdit, onDelete, onToggleFavorite }) => {
  const [copied, copy] = useCopy();

  if (!entry) {
    return (
      <section className="cp-detail cp-detail-empty">
        <div>
          <div className="cp-empty-ico"><Icon name="key" size={32} /></div>
          <h3>Sélectionnez une entrée</h3>
          <p>Cliquez sur un mot de passe pour afficher ses détails.</p>
        </div>
      </section>
    );
  }

  return (
    <section className="cp-detail" key={entry.id}>
      <div className="cp-detail-hero">
        <div className="cp-detail-hero-bg" style={{ background: `radial-gradient(120% 80% at 50% 0%, ${entry.color}55 0%, transparent 60%)` }} />
        <Avatar entry={entry} size={56} />
        <div className="cp-detail-info">
          <h1>
            {entry.name}
            {entry.favorite && (
              <span className="cp-fav-mark" title="Favori">
                <Icon name="star" size={14} color="#F59E0B" />
              </span>
            )}
          </h1>
          <a className="cp-detail-domain" href={entry.domain ? `https://${entry.domain}` : '#'}
             target="_blank" rel="noopener noreferrer"
             onClick={(e) => { if (!entry.domain) e.preventDefault(); }}>
            <Icon name="globe" size={11} />
            {entry.domain || 'Aucun domaine'}
          </a>
        </div>
        <div className="cp-detail-actions">
          {onEdit && (
            <button className="cp-btn cp-btn-ghost" onClick={onEdit}>
              <Icon name="edit" size={13} /><span>Modifier</span>
            </button>
          )}
          {(onDelete || onToggleFavorite) && (
            <MoreMenu
              favorite={entry.favorite}
              onToggleFavorite={onToggleFavorite}
              onDelete={onDelete}
            />
          )}
        </div>
      </div>

      <div className="cp-detail-body">
        <div className="cp-detail-section">
          <div className="cp-section-head">
            <h3>Comptes</h3>
            <span className="cp-section-count">{entry.accounts.length}</span>
            <span className="cp-section-spacer" />
            {onEdit && (
              <button className="cp-section-add" onClick={onEdit}>
                <Icon name="plus" size={11} /><span>Gérer</span>
              </button>
            )}
          </div>
          <div className="cp-blocks">
            {entry.accounts.map((a, i) => (
              <AccountBlock key={a.id} account={a} copied={copied} onCopy={copy} isPrimary={i === 0} />
            ))}
          </div>
        </div>

        <div className="cp-detail-section">
          <div className="cp-section-head">
            <h3>Codes 2FA</h3>
            <span className="cp-section-count">{entry.totp.length}</span>
            <span className="cp-section-spacer" />
            {onEdit && (
              <button className="cp-section-add" onClick={onEdit}>
                <Icon name="plus" size={11} /><span>Gérer</span>
              </button>
            )}
          </div>
          {entry.totp.length === 0 ? (
            <div className="cp-empty-2fa">
              <Icon name="shield" size={18} color="rgba(255,255,255,.3)" />
              <div>
                <div className="cp-empty-2fa-t">Aucun code 2FA configuré</div>
                <div className="cp-empty-2fa-s">Renforcez la sécurité de ce compte avec une vérification en deux étapes.</div>
              </div>
              {onEdit && <button className="cp-btn cp-btn-soft" onClick={onEdit}>Configurer</button>}
            </div>
          ) : (
            <div className="cp-blocks">
              {entry.totp.map(t => (
                <TotpBlock key={t.id} totp={t} copied={copied} onCopy={copy} />
              ))}
            </div>
          )}
        </div>

        <SecurityCard entry={entry} />

        {entry.notes && (
          <div className="cp-detail-section">
            <div className="cp-section-head"><h3>Notes</h3></div>
            <div className="cp-notes">{entry.notes}</div>
          </div>
        )}

        <button className="cp-enc-strip" onClick={onEncryptionInfo}>
          <div className="cp-enc-strip-ico">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <defs>
                <linearGradient id="encg" x1="0" x2="1" y1="0" y2="1">
                  <stop offset="0" stopColor="#6366F1"/>
                  <stop offset="1" stopColor="#EC4899"/>
                </linearGradient>
              </defs>
              <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke="url(#encg)" strokeWidth="1.6" fill="rgba(99,102,241,.1)"/>
              <path d="m9 12 2 2 4-4" stroke="url(#encg)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div className="cp-enc-strip-text">
            <strong>Chiffré de bout en bout</strong>
            <span>AES-256-GCM · Argon2id · Zero-knowledge</span>
          </div>
          <Icon name="chevron" size={12} color="rgba(255,255,255,.4)" />
        </button>
      </div>
    </section>
  );
};

window.Detail = Detail;
window.Field = Field;
window.MoreMenu = MoreMenu;
