/* Daily Digest email preview — rendered as inbox + HTML preview */

const EmailDigest = () => {
  const [me] = useCurrentUser();
  const toast = useToast();
  const previewRef = useRef(null);

  const copyHTML = async () => {
    const html = previewRef.current?.innerHTML || "";
    try {
      await navigator.clipboard.writeText(html);
      toast({ message: "HTML copié dans le presse-papier", tone: "green" });
    } catch (e) {
      toast({ message: "Échec copie: " + e.message, tone: "red" });
    }
  };

  const sendTest = async () => {
    const html = previewRef.current?.innerHTML || "";
    const meId = typeof me === "string" ? me : me?.id;
    const meEmail = (typeof me === "object" && me?.email) ? me.email : `${meId}@kccholdings.ca`;
    try {
      await window.kccAPI.email.send({ to: meEmail, html, subject: "Daily Digest · Test" });
      toast({ message: `Envoi test → ${meEmail}`, tone: "green" });
    } catch (e) {
      toast({ message: `Erreur envoi: ${e.message || e}`, tone: "red" });
    }
  };

  const sendDigest = async () => {
    try {
      const r = await window.kccAPI.email.dailyDigest({});
      toast({ message: `Digest envoyé · ${r.recipients || "équipe"}`, tone: "green" });
    } catch (e) {
      toast({ message: `Erreur digest: ${e.message || e}`, tone: "red" });
    }
  };

  return (
    <div className="page" style={{ maxWidth: 1300 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Daily Digest · Aperçu email</div>
          <div className="page-sub">1 email max / 24h · template HTML inline-styled · cohérent avec le portail</div>
        </div>
        <div className="row">
          <button className="btn" data-variant="ghost" onClick={copyHTML}>
            <Icon name="copy" size={13} /> Copier HTML
          </button>
          <button className="btn" onClick={sendTest}>
            <Icon name="mail" size={13} /> Envoi test
          </button>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "320px 1fr", gap: 14, alignItems: "flex-start" }}>
        {/* Inbox list */}
        <div className="card" style={{ padding: 0 }}>
          <div style={{ padding: "10px 14px", borderBottom: "1px solid var(--border-subtle)", fontSize: 12.5, fontWeight: 600 }}>Boîte de réception · {me.id}@kcc.ca</div>
          {[
            { from: "KCC Admin", subj: "📊 Daily Digest · 10 mai", preview: "2 critiques · 1 opportunité · marge stable 25.8%", time: "14:30", active: true },
            { from: "Amazon Seller", subj: "Paiement effectué · $18,400", preview: "Virement vers compte CIBC se terminant par 4421…", time: "11:18", active: false },
            { from: "Lin Mei",      subj: "Re: Échantillon diffuseur 500ml", preview: "Bonjour Kevin, nous avons expédié le lot…", time: "09:42", active: false },
            { from: "KCC Admin",    subj: "📊 Daily Digest · 9 mai",         preview: "1 critique · 4 opportunités · marge 26.1%", time: "Hier", active: false },
          ].map((m, i) => (
            <div key={i} style={{
              padding: "10px 14px", borderBottom: "1px solid var(--border-subtle)",
              background: m.active ? "var(--bg-3)" : "transparent",
              borderLeft: m.active ? "2px solid var(--accent)" : "2px solid transparent",
              cursor: "pointer"
            }}>
              <div className="between">
                <span style={{ fontSize: 12.5, fontWeight: m.active ? 600 : 500 }}>{m.from}</span>
                <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{m.time}</span>
              </div>
              <div style={{ fontSize: 12, marginTop: 2 }}>{m.subj}</div>
              <div style={{ fontSize: 11, color: "var(--text-dim)", marginTop: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{m.preview}</div>
            </div>
          ))}
        </div>

        {/* Email render */}
        <div ref={previewRef} style={{
          background: "oklch(0.1 0.005 250)",
          border: "1px solid var(--border-subtle)",
          borderRadius: 14,
          overflow: "hidden",
          maxWidth: 640, margin: "0 auto",
          boxShadow: "0 10px 40px -10px oklch(0 0 0 / 0.5)",
          fontFamily: "Inter, system-ui, sans-serif"
        }}>
          {/* Email head */}
          <div style={{ padding: "20px 24px 16px", borderBottom: "1px solid oklch(0.22 0.006 250)" }}>
            <div className="row" style={{ gap: 10, marginBottom: 12 }}>
              <div style={{ width: 28, height: 28, borderRadius: 7, background: "linear-gradient(155deg, oklch(0.78 0.17 248), oklch(0.55 0.18 258))", display: "grid", placeItems: "center", color: "white", fontWeight: 700, fontSize: 11 }}>KC</div>
              <span style={{ fontSize: 13, fontWeight: 600, color: "white" }}>KCC Holdings · Daily Digest</span>
              <span style={{ marginLeft: "auto", fontSize: 11, color: "oklch(0.5 0.01 250)", fontFamily: "JetBrains Mono" }}>10 mai 2026 · 14:30</span>
            </div>
            <div style={{ fontSize: 22, fontWeight: 600, color: "white", lineHeight: 1.2, letterSpacing: "-0.015em" }}>Bonjour {me.name}.</div>
            <div style={{ fontSize: 13, color: "oklch(0.65 0.012 250)", marginTop: 4 }}>Voici votre récap quotidien · 2 alertes critiques à traiter</div>
          </div>

          {/* KPI grid */}
          <div style={{ padding: 20 }}>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginBottom: 18 }}>
              {[
                { l: "Revenu 24h",   v: "$ 4,820",  d: "+12%", green: true },
                { l: "Marge nette",  v: "26.1%",    d: "+0.4", green: true },
                { l: "Stock j",     v: "1,842 u",  d: "-3.1%", green: false },
                { l: "Alertes",     v: "5",        d: "2 crit.", green: false, red: true },
              ].map((k, i) => (
                <div key={i} style={{ padding: 10, background: "oklch(0.165 0.006 250)", border: "1px solid oklch(0.22 0.006 250)", borderRadius: 8 }}>
                  <div style={{ fontSize: 9, color: "oklch(0.55 0.012 250)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{k.l}</div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: "white", fontFamily: "JetBrains Mono", marginTop: 3, letterSpacing: "-0.02em" }}>{k.v}</div>
                  <div style={{ fontSize: 10, color: k.red ? "oklch(0.68 0.21 24)" : k.green ? "oklch(0.74 0.16 156)" : "oklch(0.55 0.012 250)", marginTop: 2, fontFamily: "JetBrains Mono" }}>{k.d}</div>
                </div>
              ))}
            </div>

            {/* Alertes critiques */}
            <div style={{ fontSize: 11, color: "oklch(0.55 0.012 250)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8, fontWeight: 500 }}>🔴 Critique · 2</div>
            <div style={{ background: "oklch(0.68 0.21 24 / 0.08)", border: "1px solid oklch(0.68 0.21 24 / 0.25)", borderRadius: 8, padding: 12, marginBottom: 10 }}>
              <div style={{ fontSize: 13, color: "white", fontWeight: 550, marginBottom: 3 }}>Stock critique — Couvre-volant cuir 38cm</div>
              <div style={{ fontSize: 11, color: "oklch(0.7 0.012 250)" }}>12 unités · velocité 4/j · rupture estimée dans <span style={{ color: "oklch(0.68 0.21 24)", fontFamily: "JetBrains Mono" }}>3j</span></div>
            </div>
            <div style={{ background: "oklch(0.68 0.21 24 / 0.08)", border: "1px solid oklch(0.68 0.21 24 / 0.25)", borderRadius: 8, padding: 12, marginBottom: 18 }}>
              <div style={{ fontSize: 13, color: "white", fontWeight: 550, marginBottom: 3 }}>Marge négative — Tapis souris XL gaming</div>
              <div style={{ fontSize: 11, color: "oklch(0.7 0.012 250)" }}>ACOS <span style={{ color: "oklch(0.68 0.21 24)", fontFamily: "JetBrains Mono" }}>38%</span> dépasse seuil 24% · perte estimée <span style={{ fontFamily: "JetBrains Mono" }}>−$1.20/u</span></div>
            </div>

            {/* Attention */}
            <div style={{ fontSize: 11, color: "oklch(0.55 0.012 250)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8, fontWeight: 500 }}>🟡 Attention · 2 <span style={{ color: "oklch(0.4 0.012 250)", fontWeight: 400 }}>+ 0 autres</span></div>
            <div style={{ background: "oklch(0.78 0.15 75 / 0.06)", border: "1px solid oklch(0.78 0.15 75 / 0.2)", borderRadius: 8, padding: 10, marginBottom: 6, fontSize: 12, color: "oklch(0.85 0.012 250)" }}>Délai fournisseur Foshan Auto Trim · <span style={{ fontFamily: "JetBrains Mono", color: "oklch(0.78 0.15 75)" }}>+14j</span> retard</div>
            <div style={{ background: "oklch(0.78 0.15 75 / 0.06)", border: "1px solid oklch(0.78 0.15 75 / 0.2)", borderRadius: 8, padding: 10, marginBottom: 18, fontSize: 12, color: "oklch(0.85 0.012 250)" }}>BSR Diffuseur 500ml : <span style={{ fontFamily: "JetBrains Mono" }}>1245 → 1812</span> sur 7j</div>

            {/* Top margins */}
            <div style={{ fontSize: 11, color: "oklch(0.55 0.012 250)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8, fontWeight: 500 }}>🏆 Top 3 marges du jour</div>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12, marginBottom: 22 }}>
              <tbody>
                {[
                  { n: "Sac à dos isotherme 25L", a: "B07KQ4F2L9", m: 31.4 },
                  { n: "Brosse poils chien long",  a: "B08NMR2X3D", m: 30.0 },
                  { n: "Support téléphone vélo",   a: "B09L8YHT2P", m: 30.7 },
                ].map((p, i) => (
                  <tr key={i} style={{ borderBottom: "1px solid oklch(0.22 0.006 250)" }}>
                    <td style={{ padding: "8px 0", color: "white" }}>{p.n}</td>
                    <td style={{ padding: "8px 0", fontFamily: "JetBrains Mono", fontSize: 10.5, color: "oklch(0.5 0.012 250)" }}>{p.a}</td>
                    <td style={{ padding: "8px 0", textAlign: "right", fontFamily: "JetBrains Mono", fontWeight: 600, color: "oklch(0.74 0.16 156)" }}>{p.m.toFixed(1)}%</td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* CTA */}
            <a style={{
              display: "block", textAlign: "center",
              background: "linear-gradient(155deg, oklch(0.78 0.17 248), oklch(0.55 0.18 258))",
              color: "white", padding: "12px 16px", borderRadius: 8,
              fontSize: 13, fontWeight: 600, textDecoration: "none"
            }}>Ouvrir le portail →</a>

            <div style={{ marginTop: 18, paddingTop: 14, borderTop: "1px solid oklch(0.22 0.006 250)", textAlign: "center", fontSize: 10.5, color: "oklch(0.45 0.012 250)", fontFamily: "JetBrains Mono" }}>
              kcc-admin.pages.dev · envoyé via Resend · <a style={{ color: "oklch(0.6 0.012 250)" }}>Se désabonner</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.EmailDigest = EmailDigest;
