// ============================================================================
//  wifi.jsx — Pane détails Wi-Fi (QR auto-connect + identifiants).
//  QR code rendu localement (matrice déterministe) — le mot de passe ne
//  quitte jamais le navigateur.
// ============================================================================

function escapeWifi(s) {
  return String(s || '').replace(/([\\;,":])/g, '\\$1');
}

function buildWifiPayload(w) {
  const t = w.security && w.security.toUpperCase().includes('WPA') ? 'WPA'
          : w.security && w.security.toUpperCase().includes('WEP') ? 'WEP'
          : 'nopass';
  const h = w.hidden ? 'true' : 'false';
  return `WIFI:T:${t};S:${escapeWifi(w.ssid)};P:${escapeWifi(w.password)};H:${h};;`;
}

// Matrice 25×25 déterministe à partir du payload. Visuellement convaincant
// pour la maquette ; un appareil ne décode pas réellement cette image. La
// charge utile WIFI: complète est affichée en dessous, vous pouvez la
// transformer en vrai QR via un appareil externe ou une vraie lib si besoin.
function QrCode({ value, size = 200, fg = '#fff' }) {
  const N = 25;
  const bits = React.useMemo(() => {
    let h = 2166136261;
    for (let i = 0; i < value.length; i++) {
      h ^= value.charCodeAt(i);
      h = (h * 16777619) >>> 0;
    }
    const grid = Array.from({ length: N }, () => Array(N).fill(0));
    let s = h;
    for (let y = 0; y < N; y++) {
      for (let x = 0; x < N; x++) {
        s = (s * 1664525 + 1013904223) >>> 0;
        grid[y][x] = (s & 1);
      }
    }
    const drawFinder = (ox, oy) => {
      for (let y = 0; y < 7; y++) {
        for (let x = 0; x < 7; x++) {
          const onBorder = x === 0 || x === 6 || y === 0 || y === 6;
          const onInner = x >= 2 && x <= 4 && y >= 2 && y <= 4;
          grid[oy + y][ox + x] = (onBorder || onInner) ? 1 : 0;
        }
      }
      for (let y = -1; y <= 7; y++) {
        for (let x = -1; x <= 7; x++) {
          if ((x === -1 || x === 7 || y === -1 || y === 7) &&
              ox + x >= 0 && ox + x < N && oy + y >= 0 && oy + y < N) {
            grid[oy + y][ox + x] = 0;
          }
        }
      }
    };
    drawFinder(0, 0);
    drawFinder(N - 7, 0);
    drawFinder(0, N - 7);
    const ax = N - 5, ay = N - 5;
    for (let y = 0; y < 5; y++) {
      for (let x = 0; x < 5; x++) {
        const onBorder = x === 0 || x === 4 || y === 0 || y === 4;
        const onInner = x === 2 && y === 2;
        grid[ay + y][ax + x] = (onBorder || onInner) ? 1 : 0;
      }
    }
    return grid;
  }, [value]);

  const cell = size / N;
  const rects = [];
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < N; x++) {
      if (bits[y][x]) {
        rects.push(<rect key={`${x}-${y}`} x={x * cell} y={y * cell} width={cell} height={cell} rx={cell * 0.18} fill={fg} />);
      }
    }
  }

  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block', borderRadius: 8 }}>
      {rects}
    </svg>
  );
}

const WifiDetail = ({ entry, onEncryptionInfo, onEdit, onDelete, onToggleFavorite }) => {
  const [copied, copy] = useCopy();
  const [showPwd, setShowPwd] = React.useState(false);
  const payload = React.useMemo(() => buildWifiPayload(entry), [entry]);

  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%)` }} />
        <div className="cp-avatar" style={{ width: 56, height: 56, background: entry.color, fontSize: 24 }}>
          <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round">
            <path d="M2 9a14 14 0 0 1 20 0"/>
            <path d="M5 13a9 9 0 0 1 14 0"/>
            <path d="M8.5 16.5a4.5 4.5 0 0 1 7 0"/>
            <circle cx="12" cy="20" r="1.2" fill="#fff" stroke="none"/>
          </svg>
        </div>
        <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>
          <span className="cp-detail-domain">
            <Icon name="globe" size={11} />
            {entry.ssid} · {entry.security}
            {entry.hidden && <span className="cp-wifi-hidden-tag">SSID caché</span>}
          </span>
        </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-wifi-qr-card">
          <div className="cp-wifi-qr-frame">
            <QrCode value={payload} size={188} fg="#fff" />
            <div className="cp-wifi-qr-badge" style={{ background: entry.color }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round">
                <path d="M2 9a14 14 0 0 1 20 0"/>
                <path d="M5 13a9 9 0 0 1 14 0"/>
                <path d="M8.5 16.5a4.5 4.5 0 0 1 7 0"/>
                <circle cx="12" cy="20" r="1.2" fill="#fff" stroke="none"/>
              </svg>
            </div>
          </div>
          <div className="cp-wifi-qr-text">
            <h3>Connexion automatique</h3>
            <p>Scannez ce QR code avec l'appareil photo d'un iPhone ou d'un téléphone Android pour rejoindre <b>{entry.ssid}</b> sans saisir le mot de passe.</p>
            <div className="cp-wifi-payload">
              <span>Charge utile</span>
              <code>{payload}</code>
            </div>
          </div>
        </div>

        <div className="cp-detail-section">
          <div className="cp-section-head">
            <h3>Identifiants</h3>
            <span className="cp-section-spacer" />
          </div>
          <div className="cp-block">
            <Field
              label="SSID (nom du réseau)"
              value={entry.ssid}
              copied={copied === 's'}
              onCopy={() => copy('s', entry.ssid)}
            />
            <Field
              label="Mot de passe"
              value={showPwd ? entry.password : '••••••••••••••••'}
              mono
              copied={copied === 'p'}
              onCopy={() => copy('p', entry.password)}
              right={
                <button className="cp-field-eye" onClick={() => setShowPwd(!showPwd)}>
                  <Icon name={showPwd ? 'eye-off' : 'eye'} size={14} />
                </button>
              }
            />
            <Field
              label="Sécurité"
              value={entry.security}
              copied={false}
              onCopy={() => {}}
            />
          </div>
        </div>

        <div className="cp-wifi-stats">
          <div className="cp-wifi-stat">
            <div className="cp-wifi-stat-label">Type</div>
            <div className="cp-wifi-stat-value">{entry.security}</div>
          </div>
          <div className="cp-wifi-stat">
            <div className="cp-wifi-stat-label">Visibilité</div>
            <div className="cp-wifi-stat-value">{entry.hidden ? 'Cachée' : 'Diffusée'}</div>
          </div>
          <div className="cp-wifi-stat">
            <div className="cp-wifi-stat-label">Partage</div>
            <div className="cp-wifi-stat-value">{entry.shared ? 'Partagé' : 'Privé'}</div>
          </div>
          <div className="cp-wifi-stat">
            <div className="cp-wifi-stat-label">Modifié</div>
            <div className="cp-wifi-stat-value">{entry.modified || '—'}</div>
          </div>
        </div>

        {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="encgw" 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(#encgw)" strokeWidth="1.6" fill="rgba(99,102,241,.1)"/>
              <path d="m9 12 2 2 4-4" stroke="url(#encgw)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
          <div className="cp-enc-strip-text">
            <strong>QR généré localement</strong>
            <span>Le mot de passe ne quitte jamais votre appareil.</span>
          </div>
          <Icon name="chevron" size={12} color="rgba(255,255,255,.4)" />
        </button>
      </div>
    </section>
  );
};

window.WifiDetail = WifiDetail;
