/* ============================================================
   Driver sign-up — public, no-login onboarding link
   Drivers: details → availability → license photos → waiver.
   Submits a pending application HQ reviews & approves.
   ============================================================ */

const SU_DONE_KEY = "cd_signupDone";
const SU_LICENSE_CLASSES = ["Class C", "CDL-C", "CDL-B", "CDL-A"];

// read a file → downscaled JPEG data URL (keeps localStorage small)
function fileToThumb(file, cb) {
  const reader = new FileReader();
  reader.onload = (e) => {
    const img = new Image();
    img.onload = () => {
      const maxW = 560;
      const scale = Math.min(1, maxW / img.width);
      const cv = document.createElement("canvas");
      cv.width = Math.round(img.width * scale);
      cv.height = Math.round(img.height * scale);
      cv.getContext("2d").drawImage(img, 0, 0, cv.width, cv.height);
      cb(cv.toDataURL("image/jpeg", 0.55));
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
}

function SuStatusBar() {
  return (
    <div className="statusbar">
      <span>{new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</span>
      <div className="icons mono" style={{ fontSize: 11 }}><span>◗</span><span>5G</span><span>87%</span></div>
    </div>
  );
}

function DriverSignup({ state, toast }) {
  const [done, setDone] = useState(() => { try { return localStorage.getItem(SU_DONE_KEY) || ""; } catch (e) { return ""; } });
  const reset = () => { setDone(""); try { localStorage.removeItem(SU_DONE_KEY); } catch (e) {} };
  return (
    <>
      <SuStatusBar />
      <div className="g-brand">
        <span className="g-brand-mark"><Icon name="car2" style={{ width: 18, height: 18 }} /></span>
        <div><div className="g-brand-name">Driver Sign-Up</div><div className="g-brand-sub">Conference shuttle team</div></div>
      </div>
      <div className="mobile-body">
        {done
          ? <SignupDone onAgain={reset} />
          : <SignupWizard toast={toast} onDone={() => { setDone("1"); try { localStorage.setItem(SU_DONE_KEY, "1"); } catch (e) {} }} />}
      </div>
    </>
  );
}

function StepDots({ step, total }) {
  return (
    <div className="su-dots">
      {Array.from({ length: total }).map((_, i) => (
        <span key={i} className={"su-dot" + (i === step ? " on" : i < step ? " done" : "")} />
      ))}
    </div>
  );
}

function SignupWizard({ onDone, toast }) {
  const [step, setStep] = useState(0);
  const [f, setF] = useState({
    name: "", phone: "", email: "", licenseClass: "Class C", license: "", licenseExp: "",
    licenseFront: null, licenseBack: null, agree: false, signature: "",
  });
  const set = (k) => (e) => { const v = e.target.value; setF((s) => ({ ...s, [k]: v })); };

  const steps = ["You", "License", "Waiver"];
  const valid = [
    f.name.trim() && f.phone.trim() && f.license.trim(),
    f.licenseFront && f.licenseBack,
    f.agree && f.signature.trim(),
  ];

  const next = () => { if (!valid[step]) return; if (step < steps.length - 1) setStep(step + 1); else submit(); };
  const submit = () => {
    Store.addApplication({
      name: f.name.trim(), phone: f.phone.trim(), email: f.email.trim(),
      licenseClass: f.licenseClass, license: f.license.trim(), licenseExp: f.licenseExp,
      licenseFront: f.licenseFront, licenseBack: f.licenseBack,
      signature: f.signature.trim(), waiverSignedAt: Date.now(),
    });
    toast && toast("Application sent to HQ");
    onDone();
  };

  return (
    <div className="su-wrap">
      <div className="su-top">
        <div className="su-step-label">Step {step + 1} of {steps.length} · {steps[step]}</div>
        <StepDots step={step} total={steps.length} />
      </div>

      <div className="su-body g-scroll">
        {step === 0 && (
          <div className="fade-in">
            <h2 className="su-h">Tell us about you</h2>
            <p className="su-p">You’re signing up to drive for the conference shuttle team. Takes about 3 minutes.</p>
            <div className="su-field"><label className="lbl">Full name</label><input className="field" value={f.name} onChange={set("name")} placeholder="As shown on your license" autoFocus /></div>
            <div className="su-grid">
              <div className="su-field"><label className="lbl">Mobile phone</label><input className="field" value={f.phone} onChange={set("phone")} placeholder="555-0100" /></div>
              <div className="su-field"><label className="lbl">License class</label>
                <select className="field" value={f.licenseClass} onChange={set("licenseClass")}>{SU_LICENSE_CLASSES.map((c) => <option key={c}>{c}</option>)}</select>
              </div>
            </div>
            <div className="su-field"><label className="lbl">Email</label><input className="field" value={f.email} onChange={set("email")} placeholder="you@email.com" /></div>
            <div className="su-grid">
              <div className="su-field"><label className="lbl">License number</label><input className="field mono" value={f.license} onChange={set("license")} placeholder="D-0000000" /></div>
              <div className="su-field"><label className="lbl">Expires</label><input className="field" type="month" value={f.licenseExp} onChange={set("licenseExp")} /></div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div className="fade-in">
            <h2 className="su-h">Upload your license</h2>
            <p className="su-p">Take a clear photo of the front and back of your driver’s license.</p>
            <PhotoSlot label="Front of license" value={f.licenseFront} onPick={(d) => setF((s) => ({ ...s, licenseFront: d }))} />
            <PhotoSlot label="Back of license" value={f.licenseBack} onPick={(d) => setF((s) => ({ ...s, licenseBack: d }))} />
            <div className="su-reassure"><Icon name="shield" style={{ width: 15, height: 15, color: "var(--green)" }} /> Used only to verify drivers. Not shared.</div>
          </div>
        )}

        {step === 2 && (
          <div className="fade-in">
            <h2 className="su-h">Insurance & liability waiver</h2>
            <p className="su-p">Please read and sign to confirm you’re covered to drive conference guests.</p>
            <div className="waiver-doc">
              <p><b>Volunteer Driver Agreement</b></p>
              <p>I confirm that I hold a valid driver’s license of the class indicated and that it is not suspended or revoked.</p>
              <p>I agree to operate the assigned vehicle safely and lawfully, to wear a seatbelt, and to never drive while impaired or distracted.</p>
              <p>I understand the conference provides supplemental liability coverage for assigned trips, and that my own auto insurance remains primary. I release the conference and its organizers from claims arising from my own negligence.</p>
              <p>I agree to report any incident, damage, or injury to HQ immediately.</p>
            </div>
            <label className="su-agree">
              <input type="checkbox" checked={f.agree} onChange={(e) => setF({ ...f, agree: e.target.checked })} />
              <span>I have read and agree to the Volunteer Driver Agreement and insurance terms.</span>
            </label>
            <div className="su-field"><label className="lbl">Type your full name to sign</label>
              <input className="field sign-field" value={f.signature} onChange={set("signature")} placeholder="Your signature" />
            </div>
            <div className="faint" style={{ fontSize: 11.5 }}>Signed {new Date().toLocaleDateString()} · {new Date().toLocaleTimeString([], { hour: "numeric", minute: "2-digit" })}</div>
          </div>
        )}
      </div>

      <div className="su-nav">
        {step > 0 ? <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>Back</button> : <span />}
        <button className="su-next" disabled={!valid[step]} style={{ opacity: valid[step] ? 1 : 0.45 }} onClick={next}>
          {step < steps.length - 1 ? "Continue" : "Submit application"}
        </button>
      </div>
    </div>
  );
}

function PhotoSlot({ label, value, onPick }) {
  const ref = useRef(null);
  return (
    <div className="photo-slot">
      <input ref={ref} type="file" accept="image/*" capture="environment" style={{ display: "none" }}
        onChange={(e) => { const file = e.target.files[0]; if (file) fileToThumb(file, onPick); }} />
      {value ? (
        <button className="ps-filled" onClick={() => ref.current.click()}>
          <img src={value} alt={label} />
          <span className="ps-retake"><Icon name="camera" style={{ width: 14, height: 14 }} /> Retake</span>
        </button>
      ) : (
        <button className="ps-empty" onClick={() => ref.current.click()}>
          <span className="ps-ic"><Icon name="camera" /></span>
          <span className="ps-label">{label}</span>
          <span className="ps-hint">Tap to take a photo</span>
        </button>
      )}
    </div>
  );
}

function SignupDone({ onAgain }) {
  return (
    <div className="fade-in g-scroll">
      <div className="g-status-hero" style={{ paddingTop: 56 }}>
        <div className="g-done"><Icon name="check" /></div>
        <h2>You’re all signed up!</h2>
        <div className="dim" style={{ fontSize: 13.5, marginTop: 6, padding: "0 22px", lineHeight: 1.5 }}>
          HQ will review your details and license, then confirm your driving slots. Watch for a text from the dispatch team.
        </div>
      </div>
      <div className="m-cta" style={{ marginTop: 8 }}>
        <button className="secondary" onClick={onAgain}>Sign up another driver</button>
      </div>
    </div>
  );
}

Object.assign(window, { DriverSignup });
