/* global React */
const { useState, useEffect, useRef } = window.ReactHooks;

function LoginView({ onLogin }) {
  const [email, setEmail] = useState("admin@tcviz.com");
  const [pw, setPw] = useState("••••••••");
  const [err, setErr] = useState("");

  return (
    <div className="admin-wrap">
      <div className="login-card">
        <div className="brand" style={{ marginBottom: 32 }}>
          <span className="brand-mark">TC</span>
          <span>admin</span>
        </div>
        <h2>Sign in</h2>
        <p>TC Admin · upload, manage and release Power BI visual packages.</p>
        <form onSubmit={(e) => { e.preventDefault(); if (!email || !pw) { setErr("Missing credentials"); return; } onLogin(email); }}>
          <div className="field">
            <label>Email</label>
            <input value={email} onChange={(e) => setEmail(e.target.value)} />
          </div>
          <div className="spacer-4" />
          <div className="field">
            <label>Password</label>
            <input type="password" value={pw} onChange={(e) => setPw(e.target.value)} />
          </div>
          <div className="spacer-6" />
          {err && <div style={{ color: "var(--danger)", fontSize: 13, marginBottom: 12 }}>{err}</div>}
          <button type="submit" className="btn" style={{ width: "100%", justifyContent: "center" }}>Sign in →</button>
          <div style={{ marginTop: 16, textAlign: "center", fontFamily: "var(--f-mono)", fontSize: 11, color: "var(--muted)", letterSpacing: "0.08em", textTransform: "uppercase" }}>
            Demo build · any credentials accepted
          </div>
        </form>
      </div>
    </div>
  );
}

function AdminPanel({ email, onLogout }) {
  const [section, setSection] = useState("Uploads");
  const [files, setFiles] = useState([
    { name: "horizon-kpi-2.4.1.pbiviz", size: "182 KB", status: "Published", date: "2026-03-18", v: "2.4.1" },
    { name: "strata-waterfall-1.9.0.pbiviz", size: "148 KB", status: "Published", date: "2026-02-11", v: "1.9.0" },
    { name: "atlas-small-multiples-3.0.2.pbiviz", size: "221 KB", status: "Published", date: "2026-04-02", v: "3.0.2" },
    { name: "meridian-map-4.1.0.pbiviz", size: "398 KB", status: "Pending review", date: "2026-03-30", v: "4.1.0" },
    { name: "orbit-network-0.9.2.pbiviz", size: "312 KB", status: "Failed signing", date: "2026-04-12", v: "0.9.2" }
  ]);
  const [drag, setDrag] = useState(false);
  const [uploading, setUploading] = useState(null);
  const inputRef = useRef(null);

  const statusClass = (s) => s === "Published" ? "ok" : s === "Pending review" ? "pending" : "err";

  const onFiles = (fl) => {
    const f = fl[0];
    if (!f) return;
    const sizeKB = Math.max(1, Math.round(f.size / 1024));
    setUploading({ name: f.name, progress: 0 });
    const iv = setInterval(() => {
      setUploading((u) => {
        if (!u) return u;
        const next = Math.min(100, u.progress + 7 + Math.random() * 8);
        if (next >= 100) {
          clearInterval(iv);
          setFiles((list) => [{
            name: f.name,
            size: sizeKB + " KB",
            status: "Pending review",
            date: new Date().toISOString().slice(0, 10),
            v: "—"
          }, ...list]);
          setTimeout(() => setUploading(null), 400);
          return { ...u, progress: 100 };
        }
        return { ...u, progress: next };
      });
    }, 140);
  };

  return (
    <div className="admin-layout">
      <aside className="admin-side">
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 32 }}>
          <div className="brand">
            <span className="brand-mark">TC</span>
            <span>admin</span>
          </div>
        </div>

        <div className="group">
          <h4>Library</h4>
          {["Uploads", "Visuals", "Releases"].map((n) => (
            <a key={n} href="#" className={section === n ? "on" : ""} onClick={(e) => { e.preventDefault(); setSection(n); }}>{n}</a>
          ))}
        </div>
        <div className="group">
          <h4>Commerce</h4>
          {["Customers", "Licenses", "Invoices"].map((n) => (
            <a key={n} href="#" className={section === n ? "on" : ""} onClick={(e) => { e.preventDefault(); setSection(n); }}>{n}</a>
          ))}
        </div>
        <div className="group">
          <h4>Operations</h4>
          {["Hostinger", "Logs", "Settings"].map((n) => (
            <a key={n} href="#" className={section === n ? "on" : ""} onClick={(e) => { e.preventDefault(); setSection(n); }}>{n}</a>
          ))}
        </div>

        <div style={{ marginTop: "auto", paddingTop: 40, fontSize: 12, color: "var(--muted)" }}>
          <div className="mono" style={{ fontSize: 10, letterSpacing: "0.08em", textTransform: "uppercase" }}>Signed in</div>
          <div style={{ marginTop: 6, color: "var(--fg)" }}>{email}</div>
          <button className="btn btn-ghost btn-sm" style={{ marginTop: 12 }} onClick={onLogout}>Sign out</button>
        </div>
      </aside>

      <main className="admin-main">
        {section === "Uploads" && (
          <>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginBottom: 32 }}>
              <div>
                <div className="eyebrow">Visual packages</div>
                <h2 className="display" style={{ fontSize: 40, margin: "8px 0 0", letterSpacing: "-0.02em" }}>Uploads</h2>
              </div>
              <div style={{ display: "flex", gap: 12 }}>
                <span className="mono" style={{ fontSize: 11, letterSpacing: "0.08em", color: "var(--muted)", textTransform: "uppercase", alignSelf: "center" }}>
                  Destination · Hostinger · /pbiviz/
                </span>
                <button className="btn" onClick={() => inputRef.current && inputRef.current.click()}>Upload .pbiviz</button>
              </div>
            </div>

            <div
              className={"uploader " + (drag ? "drag" : "")}
              onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
              onDragLeave={() => setDrag(false)}
              onDrop={(e) => { e.preventDefault(); setDrag(false); onFiles(e.dataTransfer.files); }}
              onClick={() => inputRef.current && inputRef.current.click()}
            >
              <div className="t">Drop a .pbiviz package to publish</div>
              <div className="s">or click to choose · Files are uploaded to your Hostinger account, signed and queued for review</div>
              <input ref={inputRef} type="file" accept=".pbiviz,.zip" onChange={(e) => onFiles(e.target.files)} />
            </div>

            {uploading && (
              <div style={{ marginTop: 24, border: "1px solid var(--line-soft)", padding: 16 }}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8, fontSize: 13 }}>
                  <span className="mono">{uploading.name}</span>
                  <span className="mono num">{Math.floor(uploading.progress)}%</span>
                </div>
                <div className="progress"><i style={{ width: uploading.progress + "%" }} /></div>
              </div>
            )}

            <table className="file-table">
              <thead>
                <tr><th>Package</th><th>Version</th><th>Size</th><th>Uploaded</th><th>Status</th><th></th></tr>
              </thead>
              <tbody>
                {files.map((f, i) => (
                  <tr key={i}>
                    <td className="mono">{f.name}</td>
                    <td className="num">{f.v}</td>
                    <td className="num">{f.size}</td>
                    <td className="num">{f.date}</td>
                    <td><span className={"status-pill " + statusClass(f.status)}>{f.status}</span></td>
                    <td style={{ textAlign: "right" }}>
                      <button className="btn btn-ghost btn-sm">Open</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </>
        )}

        {section !== "Uploads" && (
          <div style={{ padding: "120px 0", textAlign: "center", color: "var(--muted)" }}>
            <div className="eyebrow" style={{ marginBottom: 16 }}>Section · {section}</div>
            <div className="display" style={{ fontSize: 32, color: "var(--fg)" }}>Coming soon</div>
            <p style={{ marginTop: 12 }}>This area of the admin is a placeholder in the current build.</p>
          </div>
        )}
      </main>
    </div>
  );
}

function AdminPage() {
  const [email, setEmail] = useState(() => sessionStorage.getItem("tcviz_admin_email") || "");
  useEffect(() => {
    if (email) sessionStorage.setItem("tcviz_admin_email", email);
    else sessionStorage.removeItem("tcviz_admin_email");
  }, [email]);
  return email ? <AdminPanel email={email} onLogout={() => setEmail("")} /> : <LoginView onLogin={setEmail} />;
}

window.AdminPage = AdminPage;
