// affiliate.jsx — MilletsFit Affiliate portal (login + dashboard)
// Uses globals: BRAND, serif, sans, mono

const { useState: useStateA, useEffect: useEffectA, useCallback: useCallbackA } = React;

const AF_STATUS = {
  pending_payment: ["Pending", "#f59e0b"],
  confirmed: ["Order Received", "#10b981"],
  preparing: ["Preparing", "#6366f1"],
  packing: ["Packing", "#14b8a6"],
  delivering: ["Handed to Delivery", "#3b82f6"],
  completed: ["Completed", "#059669"],
  cancelled: ["Cancelled", "#ef4444"],
  paused: ["Paused", "#8b5cf6"],
};

const aed2 = (n) => `AED ${Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

function afApi(path, opts = {}) {
  const token = sessionStorage.getItem("mf_affiliate_token");
  return fetch(path, {
    ...opts,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(opts.headers || {}),
    },
  });
}

const afField = { width: "100%", padding: "12px 14px", border: `1px solid ${BRAND.creamD}`, borderRadius: 8, fontFamily: sans, fontSize: 14, color: BRAND.ink, outline: "none", background: "#fff" };
const afLabel = { fontFamily: mono, fontSize: 10.5, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.goldD, display: "block", marginBottom: 6 };

/* ── Login panel ── */
function LoginPanel({ onLogin }) {
  const [email, setEmail] = useStateA("");
  const [password, setPassword] = useStateA("");
  const [error, setError] = useStateA(null);
  const [loading, setLoading] = useStateA(false);

  async function submit(e) {
    e.preventDefault();
    setLoading(true); setError(null);
    try {
      const resp = await fetch("/api/affiliate?action=login", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = await resp.json();
      if (resp.ok) { sessionStorage.setItem("mf_affiliate_token", data.token); onLogin(); }
      else setError(data.error || "Login failed");
    } catch { setError("Connection failed. Try again."); }
    setLoading(false);
  }

  return (
    <form onSubmit={submit}>
      {error && <div style={{ background: "#fef2f2", border: "1px solid #fca5a5", color: "#991b1b", padding: "10px 14px", borderRadius: 8, fontSize: 13, marginBottom: 18 }}>{error}</div>}
      <label style={{ display: "block", marginBottom: 16 }}>
        <span style={afLabel}>Email</span>
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required style={afField} />
      </label>
      <label style={{ display: "block", marginBottom: 24 }}>
        <span style={afLabel}>Password</span>
        <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required style={afField} />
      </label>
      <button type="submit" disabled={loading} style={{ width: "100%", cursor: loading ? "wait" : "pointer", border: "none", background: BRAND.forest, color: "#fff", fontFamily: sans, fontWeight: 600, fontSize: 15, padding: "14px 24px", borderRadius: 999, opacity: loading ? 0.7 : 1 }}>
        {loading ? "Signing in..." : "Sign in"}
      </button>
    </form>
  );
}

/* ── Application panel ── */
const SOCIALS = [
  ["instagram", "Instagram"], ["tiktok", "TikTok"], ["youtube", "YouTube"],
  ["facebook", "Facebook"], ["x", "X (Twitter)"], ["snapchat", "Snapchat"], ["linkedin", "LinkedIn"],
];

function ApplyPanel() {
  const [name, setName] = useStateA("");
  const [email, setEmail] = useStateA("");
  const [socials, setSocials] = useStateA({});
  const [otherOn, setOtherOn] = useStateA(false);
  const [submitting, setSubmitting] = useStateA(false);
  const [error, setError] = useStateA(null);
  const [done, setDone] = useStateA(false);

  function setSocial(k, v) { setSocials((s) => ({ ...s, [k]: v })); }

  async function submit(e) {
    e.preventDefault();
    setError(null);
    const filled = Object.fromEntries(Object.entries(socials).filter(([, v]) => v && v.trim()));
    if (otherOn && !((socials.other || "").trim())) { setError("Please specify your 'Other' platform, or untick it."); return; }
    if (Object.keys(filled).length === 0) { setError("Please add at least one social profile."); return; }
    setSubmitting(true);
    try {
      const resp = await fetch("/api/affiliate?action=apply", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, email, socials: filled }),
      });
      const data = await resp.json();
      if (resp.ok) setDone(true);
      else setError(data.error || "Could not submit. Try again.");
    } catch { setError("Connection failed. Try again."); }
    setSubmitting(false);
  }

  if (done) {
    return (
      <div style={{ textAlign: "center", padding: "10px 0" }}>
        <div style={{ fontSize: 40, marginBottom: 10 }}>🌾</div>
        <h3 style={{ fontFamily: serif, fontSize: 20, fontWeight: 700, color: BRAND.forest, margin: "0 0 8px" }}>Application received</h3>
        <p style={{ fontSize: 14, color: BRAND.body, lineHeight: 1.6, margin: 0 }}>Thanks! We'll review your profile and email you if you're approved.</p>
      </div>
    );
  }

  return (
    <form onSubmit={submit}>
      <p style={{ fontSize: 13.5, color: BRAND.body, lineHeight: 1.6, margin: "0 0 18px" }}>Share MilletsFit with your audience, give them a discount, and earn commission on every sale. Apply below and we'll be in touch.</p>
      {error && <div style={{ background: "#fef2f2", border: "1px solid #fca5a5", color: "#991b1b", padding: "10px 14px", borderRadius: 8, fontSize: 13, marginBottom: 16 }}>{error}</div>}
      <label style={{ display: "block", marginBottom: 14 }}><span style={afLabel}>Full name</span><input value={name} onChange={(e) => setName(e.target.value)} required style={afField} /></label>
      <label style={{ display: "block", marginBottom: 18 }}><span style={afLabel}>Email</span><input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required style={afField} /></label>

      <span style={{ ...afLabel, marginBottom: 8 }}>Your socials <span style={{ textTransform: "none", letterSpacing: 0, color: BRAND.body }}>— add at least one</span></span>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 10 }}>
        {SOCIALS.map(([k, label]) => (
          <input key={k} value={socials[k] || ""} onChange={(e) => setSocial(k, e.target.value)} placeholder={label} style={{ ...afField, fontSize: 13 }} />
        ))}
      </div>
      <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: BRAND.body, marginBottom: otherOn ? 8 : 20, cursor: "pointer" }}>
        <input type="checkbox" checked={otherOn} onChange={(e) => { setOtherOn(e.target.checked); if (!e.target.checked) setSocial("other", ""); }} /> Other — please specify
      </label>
      {otherOn && (
        <input value={socials.other || ""} onChange={(e) => setSocial("other", e.target.value)} placeholder="Platform + handle (e.g. Threads @sarah)" style={{ ...afField, fontSize: 13, marginBottom: 20 }} />
      )}

      <button type="submit" disabled={submitting} style={{ width: "100%", cursor: submitting ? "wait" : "pointer", border: "none", background: BRAND.forest, color: "#fff", fontFamily: sans, fontWeight: 600, fontSize: 15, padding: "14px 24px", borderRadius: 999, opacity: submitting ? 0.7 : 1 }}>
        {submitting ? "Submitting..." : "Apply to become an affiliate"}
      </button>
    </form>
  );
}

/* ── Public landing (apply / login toggle) ── */
function PublicLanding({ onLogin }) {
  const [mode, setMode] = useStateA("apply");
  const tab = (key, label) => (
    <button type="button" onClick={() => setMode(key)} style={{ flex: 1, cursor: "pointer", border: "none", background: mode === key ? BRAND.forest : "transparent", color: mode === key ? "#fff" : BRAND.forest, fontFamily: sans, fontSize: 13, fontWeight: 600, padding: "10px 12px", borderRadius: 8 }}>{label}</button>
  );
  return (
    <div style={{ minHeight: "100vh", display: "flex", alignItems: "flex-start", justifyContent: "center", background: "#F9F6F0", fontFamily: sans, padding: "48px 20px" }}>
      <div style={{ background: "#fff", padding: "40px 36px", width: 460, maxWidth: "92vw", border: `1px solid ${BRAND.creamD}`, boxShadow: "0 24px 60px rgba(27,58,45,.1)" }}>
        <div style={{ textAlign: "center", marginBottom: 22 }}>
          <h1 style={{ fontFamily: serif, fontSize: 28, fontWeight: 700, color: BRAND.forest, margin: "0 0 6px" }}>MilletsFit</h1>
          <p style={{ fontFamily: mono, fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase", color: BRAND.goldD, margin: 0 }}>Affiliate Program</p>
        </div>
        <div style={{ display: "flex", gap: 6, background: BRAND.cream, border: `1px solid ${BRAND.creamD}`, borderRadius: 10, padding: 4, marginBottom: 24 }}>
          {tab("apply", "Become an affiliate")}
          {tab("login", "Affiliate login")}
        </div>
        {mode === "apply" ? <ApplyPanel /> : <LoginPanel onLogin={onLogin} />}
      </div>
    </div>
  );
}

function StatCard({ label, value, accent }) {
  return (
    <div style={{ background: "#fff", border: `1px solid ${BRAND.creamD}`, padding: "20px 22px" }}>
      <div style={{ fontFamily: mono, fontSize: 10, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.goldD, marginBottom: 8 }}>{label}</div>
      <div style={{ fontFamily: serif, fontSize: 26, fontWeight: 700, color: accent || BRAND.forest }}>{value}</div>
    </div>
  );
}

/* ── Dashboard ── */
function AffiliateDashboard() {
  const [data, setData] = useStateA(null);
  const [loading, setLoading] = useStateA(true);
  const [copied, setCopied] = useStateA(false);

  const load = useCallbackA(async () => {
    const resp = await afApi("/api/affiliate?action=dashboard");
    if (resp.ok) setData(await resp.json());
    setLoading(false);
  }, []);
  useEffectA(() => { load(); }, [load]);

  if (loading) return <div style={{ padding: 60, textAlign: "center", color: BRAND.body }}>Loading…</div>;
  if (!data) return <div style={{ padding: 60, textAlign: "center", color: "#c44" }}>Could not load your dashboard.</div>;

  const link = `${window.location.origin}/plans?ref=${data.code}`;
  function copyLink() {
    navigator.clipboard.writeText(link).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1800); });
  }

  return (
    <div style={{ maxWidth: 1000, margin: "0 auto", padding: "32px 24px" }}>
      {/* Your link */}
      <div style={{ background: "#fff", border: `1px solid ${BRAND.creamD}`, padding: "24px 26px", marginBottom: 22 }}>
        <div style={{ fontFamily: mono, fontSize: 10.5, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.goldD, marginBottom: 10 }}>Your affiliate link</div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
          <code style={{ flex: 1, minWidth: 240, background: BRAND.cream, border: `1px solid ${BRAND.creamD}`, borderRadius: 8, padding: "12px 14px", fontFamily: mono, fontSize: 13.5, color: BRAND.forest, wordBreak: "break-all" }}>{link}</code>
          <button onClick={copyLink} style={{ cursor: "pointer", border: "none", background: BRAND.forest, color: "#fff", fontFamily: sans, fontWeight: 600, fontSize: 13.5, padding: "12px 20px", borderRadius: 8 }}>
            {copied ? "Copied ✓" : "Copy link"}
          </button>
        </div>
        <p style={{ fontSize: 13, color: BRAND.body, margin: "12px 0 0", lineHeight: 1.5 }}>
          Share this link. Anyone who orders through it gets <strong>{data.discountPercent}% off</strong>, and you earn <strong>{data.commissionPercent}% commission</strong> on each net sale. Code: <strong>{data.code}</strong>
        </p>
      </div>

      {/* Totals */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 22 }} className="mf-af-stats">
        <StatCard label="Paid referrals" value={data.totals.eligibleOrders} />
        <StatCard label="Net sales driven" value={aed2(data.totals.netSales)} />
        <StatCard label="Commission earned" value={aed2(data.totals.commission)} accent={BRAND.greenMed} />
      </div>

      {/* Referrals */}
      <div style={{ background: "#fff", border: `1px solid ${BRAND.creamD}` }}>
        <div style={{ padding: "16px 20px", borderBottom: `2px solid ${BRAND.creamD}`, fontFamily: serif, fontSize: 18, fontWeight: 700, color: BRAND.forest }}>Who used your link</div>
        <div style={{ overflowX: "auto" }}>
          <div style={{ minWidth: 640 }}>
            <div style={{ display: "grid", gridTemplateColumns: "100px 1fr 1.3fr 130px 110px 110px", gap: 12, padding: "12px 20px", borderBottom: `1px solid ${BRAND.creamD}`, fontFamily: mono, fontSize: 10, letterSpacing: ".06em", textTransform: "uppercase", color: BRAND.goldD }}>
              <span>Date</span><span>Customer</span><span>Plan</span><span>Status</span><span>Net sale</span><span>Commission</span>
            </div>
            {data.referrals.map((r, i) => {
              const [lbl, col] = AF_STATUS[r.status] || [r.status, "#888"];
              return (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "100px 1fr 1.3fr 130px 110px 110px", gap: 12, padding: "13px 20px", borderBottom: `1px solid ${BRAND.creamD}`, fontSize: 13, color: BRAND.body, alignItems: "center", opacity: r.eligible ? 1 : 0.55 }}>
                  <span style={{ fontSize: 12 }}>{r.date}</span>
                  <span style={{ fontWeight: 600, color: BRAND.forest }}>{r.customer}</span>
                  <span style={{ fontSize: 12.5 }}>{r.plans}</span>
                  <span><span style={{ display: "inline-block", padding: "3px 9px", borderRadius: 999, fontSize: 10.5, fontWeight: 600, color: "#fff", background: col }}>{lbl}</span></span>
                  <span>{r.eligible ? aed2(r.netSale) : "—"}</span>
                  <span style={{ fontWeight: 600, color: r.eligible ? BRAND.greenMed : BRAND.body }}>{r.eligible ? aed2(r.commission) : "—"}</span>
                </div>
              );
            })}
            {data.referrals.length === 0 && (
              <div style={{ padding: "40px 20px", textAlign: "center", color: BRAND.body, fontSize: 14 }}>No referrals yet — share your link to get started.</div>
            )}
          </div>
        </div>
      </div>
      <p style={{ fontSize: 11.5, color: BRAND.body, marginTop: 14, lineHeight: 1.5 }}>
        Commission is counted on paid orders and removed if an order is cancelled or refunded. Cancelled/pending orders are shown greyed out.
      </p>
    </div>
  );
}

/* ── App shell ── */
function AffiliateApp() {
  const [authed, setAuthed] = useStateA(!!sessionStorage.getItem("mf_affiliate_token"));
  if (!authed) return <PublicLanding onLogin={() => setAuthed(true)} />;

  function logout() { sessionStorage.removeItem("mf_affiliate_token"); setAuthed(false); }

  return (
    <div style={{ minHeight: "100vh", background: "#F9F6F0", fontFamily: sans }}>
      <header style={{ background: BRAND.forest, color: "#fff", padding: "14px 24px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <h1 style={{ fontFamily: serif, fontSize: 20, fontWeight: 700, margin: 0 }}>MilletsFit</h1>
          <span style={{ fontFamily: mono, fontSize: 10, letterSpacing: ".08em", textTransform: "uppercase", background: "rgba(255,255,255,.15)", padding: "3px 9px", borderRadius: 999 }}>Affiliate</span>
        </div>
        <button onClick={logout} style={{ cursor: "pointer", border: "none", background: "rgba(255,255,255,.1)", color: "#fff", fontFamily: sans, fontSize: 12, fontWeight: 500, padding: "6px 14px", borderRadius: 6 }}>Sign out</button>
      </header>
      <AffiliateDashboard />
    </div>
  );
}

Object.assign(window, { AffiliateApp });
