/* global window React */

const { useState, useEffect, useRef } = React;
const { I } = window;

// ─── Top nav ────────────────────────────────────────────────────────────
function TopNav({ user, page, onNavigate, onLogout, breadcrumb }) {
  return (
    <header className="rac-nav">
      <button className="rac-nav__brand" onClick={() => onNavigate(user?.role === "registrant" ? "registrant.dashboard" : user?.role === "regulator" ? "regulator.dashboard" : "login")}>
        <span className="rac-nav__mark">
          <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 18 L4 8 L12 4 L20 8 L20 18" />
            <path d="M9 14 L11.5 16.5 L16 12" />
          </svg>
        </span>
        <div style={{display:"flex", flexDirection:"column", alignItems:"flex-start"}}>
          <span className="rac-nav__title">USEPA RaC Platform</span>
        </div>
      </button>

      {breadcrumb && (
        <div className="rac-nav__crumbs">
          <span className="sep">/</span>
          <strong>{breadcrumb}</strong>
        </div>
      )}

      <div className="rac-nav__spacer" />

      {user && (
        <>
          <span className={`rac-nav__role ${user.role === "regulator" ? "is-regulator" : ""}`}>
            <span className="dot">{user.initials}</span>
            <span style={{display:"flex", flexDirection:"column", lineHeight:1.15}}>
              <span style={{fontSize:11, fontWeight:600, opacity:0.7, textTransform:"uppercase", letterSpacing:"0.05em"}}>
                {user.role === "regulator" ? "Regulator" : "Registrant"}
              </span>
              <span style={{fontSize:12, fontWeight:600}}>{user.name}</span>
            </span>
          </span>
          <button className="rac-nav__btn" onClick={onLogout}>
            <I.Logout size={14} />
            Sign out
          </button>
        </>
      )}
    </header>
  );
}

// ─── Footer ─────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer className="rac-footer">
      <span>USEPA OPPTS 860.1500 · Rules-as-Code Platform</span>
      <span className="rac-footer__pill">Mock-up - Not for Production Use</span>
      <span style={{marginLeft:"auto"}}>Designed and developed by <strong style={{color:"var(--rac-ink-2)"}}>Creme Global</strong></span>
    </footer>
  );
}

// ─── Step indicator (sidebar) ──────────────────────────────────────────
const STEP_DEFS = [
  { id: "a1", page: "registrant.a1", label: "Crop selection",    hint: "Select crop group",      icon: I.Crop },
  { id: "a2", page: "registrant.a2", label: "GAP conditions",    hint: "Confirm application",    icon: I.Form },
  { id: "a3", page: "registrant.a3", label: "Trial data",        hint: "Upload demo file",       icon: I.Upload },
  { id: "a4", page: "registrant.a4", label: "Decision tree",     hint: "View assessment logic",  icon: I.Tree },
  { id: "a5", page: "registrant.a5", label: "Output report",     hint: "Review pass/fail",       icon: I.Report },
  { id: "a6", page: "registrant.a6", label: "Submit for review", hint: "Send to regulator",      icon: I.Send },
];

function StepIndicator({ page, submission, onNavigate }) {
  const sc = stepCompletion(submission);
  return (
    <aside className="rac-steps">
      <div className="rac-steps__title">New submission</div>
      {STEP_DEFS.map((s, idx) => {
        const isActive = page === s.page;
        const complete = sc[s.id];
        const locked = (s.id === "a5" && !sc.a5_unlocked) || (s.id === "a6" && !sc.a6_unlocked);
        return (
          <button
            key={s.id}
            className={`rac-step ${isActive ? "is-active" : ""} ${complete ? "is-complete" : ""} ${locked ? "is-locked" : ""}`}
            onClick={() => !locked && onNavigate(s.page)}
            disabled={locked}
          >
            <span className="rac-step__dot">
              {complete ? <I.Check size={14} /> : locked ? <I.Lock size={11} /> : (idx+1)}
            </span>
            <span className="rac-step__body">
              <span className="rac-step__label">{s.label}</span>
              <span className="rac-step__hint">{stepHint(s.id, submission) || s.hint}</span>
            </span>
          </button>
        );
      })}

      <div style={{padding:"24px 12px 0", borderTop:"1px solid var(--rac-line)", marginTop:16}}>
        <div className="rac-steps__title" style={{padding:"0 0 10px"}}>Submission</div>
        <div style={{fontSize:12, color:"var(--rac-muted)", lineHeight:1.5}}>
          <div><strong style={{color:"var(--rac-ink)"}}>Reference</strong></div>
          <div className="rac-mono">{submission.selectedDemoFile === "fail" ? "DEMO-002" : submission.selectedDemoFile === "pass" ? "DEMO-001" : "-"}</div>
          <div style={{marginTop:8}}><strong style={{color:"var(--rac-ink)"}}>Started</strong> Apr 30, 2026</div>
        </div>
      </div>
    </aside>
  );
}

function stepCompletion(s) {
  const a1 = s.crop !== null;
  const a2 = s.gapConfirmed;
  const a3 = s.selectedDemoFile !== null;
  const a4 = true;
  const a5_unlocked = a1 && a2 && a3;
  const a5 = a5_unlocked && s.reportViewed;
  const a6_unlocked = a5;
  const a6 = s.submitted;
  return { a1, a2, a3, a4, a5, a5_unlocked, a6, a6_unlocked };
}
function stepHint(id, s) {
  if (id === "a1" && s.crop)            return s.crop;
  if (id === "a2" && s.gapConfirmed)    return "GAP confirmed";
  if (id === "a3" && s.selectedDemoFile) return "Valid file uploaded";
  if (id === "a6" && s.submitted)       return "Submitted";
  return null;
}

// ─── Modal ──────────────────────────────────────────────────────────────
function Modal({ open, onClose, children }) {
  if (!open) return null;
  return (
    <div className="rac-modal-overlay" onClick={onClose}>
      <div className="rac-modal" onClick={(e) => e.stopPropagation()}>{children}</div>
    </div>
  );
}

// ─── Pill helper ────────────────────────────────────────────────────────
function ResultPill({ value }) {
  const map = {
    PASS:    { cls: "pass",  label: "Pass",   icon: <I.Check size={12} /> },
    FAIL:    { cls: "fail",  label: "Fail",   icon: <I.X size={12} /> },
    BELOW:   { cls: "warn",  label: "Below",  icon: <I.Alert size={12} /> },
    NOT_REQUIRED: { cls: "mute", label: "Not required", icon: null },
    "-":     { cls: "mute",  label: "-",      icon: null },
    "Pending Review": { cls: "info", label: "Pending", icon: null },
    "Approved": { cls: "pass", label: "Approved", icon: <I.Check size={12} /> },
    "Rejected": { cls: "fail", label: "Rejected", icon: <I.X size={12} /> },
    "Under Review": { cls: "warn", label: "Under Review", icon: null },
  };
  const m = map[value] || { cls: "mute", label: String(value), icon: null };
  return <span className={`rac-pill rac-pill--${m.cls}`}>{m.icon}{m.label}</span>;
}

window.TopNav = TopNav;
window.Footer = Footer;
window.StepIndicator = StepIndicator;
window.Modal = Modal;
window.ResultPill = ResultPill;
window.stepCompletion = stepCompletion;
