/* global React, Icon */
const { useState: useStateMod, useEffect: useEffectMod } = React;

function AppraisalModal({ open, onClose, initialCategory }) {
  const [step, setStep] = useStateMod(0);
  const [data, setData] = useStateMod({
    category: "", brand: "", piece: "", year: "", photos: [],
    firstName: "", lastName: "", email: "", phone: "", notes: ""
  });

  useEffectMod(() => {
    if (open) {
      setStep(0);
      setData(d => ({ ...d, category: initialCategory || "" }));
    }
  }, [open, initialCategory]);

  useEffectMod(() => {
    function onKey(e) { if (e.key === "Escape" && open) onClose(); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  useEffectMod(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  function update(k, v) { setData(d => ({ ...d, [k]: v })); }

  const stepNames = ["Piece", "Details", "Contact"];
  const isLast = step === 3;
  const canAdvance = step === 0 ? !!data.category :
                     step === 1 ? !!data.brand && data.photos.length > 0 :
                     step === 2 ? !!data.firstName && !!data.lastName && !!data.email : true;

  return (
    <div className={`modal-backdrop ${open ? "open" : ""}`} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        {!isLast && (
          <>
            <div className="modal-header">
              <div>
                <span className="eyebrow">Free Valuation</span>
                <h3>Tell us what you're considering selling.</h3>
              </div>
              <button className="modal-close" onClick={onClose} aria-label="Close">
                <Icon.X />
              </button>
            </div>

            <div className="modal-progress">
              {stepNames.map((n, i) => (
                <React.Fragment key={n}>
                  <div className={`step-dot ${i === step ? "active" : i < step ? "done" : ""}`}>
                    <span className="num">{i < step ? "✓" : (i + 1).toString().padStart(2, "0")}</span>
                    <span className="name">{n}</span>
                  </div>
                  {i < 2 && <span className="sep" />}
                </React.Fragment>
              ))}
            </div>

            <div className="modal-body">
              {step === 0 && <Step1 data={data} update={update} />}
              {step === 1 && <Step2 data={data} update={update} />}
              {step === 2 && <Step3 data={data} update={update} />}
            </div>

            <div className="modal-footer">
              <button
                className="secondary"
                onClick={() => setStep(s => Math.max(0, s - 1))}
                disabled={step === 0}
              >
                ← Back
              </button>
              <button
                className="btn btn-gold"
                onClick={() => {
                  if (!canAdvance) return;
                  if (step < 2) setStep(s => s + 1);
                  else setStep(3);
                }}
                style={{ opacity: canAdvance ? 1 : 0.4, pointerEvents: canAdvance ? "auto" : "none" }}
              >
                {step < 2 ? "Continue" : "Request valuation"}
                <Icon.Arrow />
              </button>
            </div>
          </>
        )}

        {isLast && (
          <div className="modal-success">
            <div className="check"><Icon.Check size={28} /></div>
            <h3>Thank you, {data.firstName || "there"}.</h3>
            <p>
              A specialist from our Beverly Hills office will reach out within one business day to schedule your valuation — by appointment, with full discretion.
            </p>
            <button className="btn btn-outline-navy" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

function Step1({ data, update }) {
  const cats = [
    { id: "watches", name: "Watches", ex: "Rolex, Patek, AP, Cartier", icon: <Icon.Watch /> },
    { id: "jewelry", name: "Jewelry", ex: "Diamond, signed, vintage", icon: <Icon.Gem /> },
    { id: "handbags", name: "Handbags", ex: "Hermès, Chanel, Louis Vuitton", icon: <Icon.Bag /> },
  ];
  return (
    <>
      <div className="step-title">What are you considering selling?</div>
      <div className="step-help">Select a category to begin. You can add more pieces later.</div>
      <div className="cat-grid">
        {cats.map(c => (
          <button
            key={c.id}
            className={`cat-tile ${data.category === c.id ? "selected" : ""}`}
            onClick={() => update("category", c.id)}
          >
            <span className="icon">{c.icon}</span>
            <span className="name">{c.name}</span>
            <span className="ex">{c.ex}</span>
          </button>
        ))}
      </div>
    </>
  );
}

function PhotoUpload({ photos = [], update }) {
  const inputRef = React.useRef(null);
  function add(e) {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    const mapped = files.map(f => ({ name: f.name, url: URL.createObjectURL(f) }));
    update("photos", [...photos, ...mapped]);
    e.target.value = "";
  }
  function remove(i) {
    const next = photos.slice();
    const [rm] = next.splice(i, 1);
    if (rm && rm.url) URL.revokeObjectURL(rm.url);
    update("photos", next);
  }
  return (
    <div className="photo-upload">
      <button type="button" className="photo-drop" onClick={() => inputRef.current && inputRef.current.click()}>
        <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="3" width="18" height="18" /><circle cx="8.5" cy="9" r="1.5" /><path d="M21 15l-5-5L5 21" />
        </svg>
        <span className="photo-drop-title">{photos.length ? "Add more photos" : "Add photos"}</span>
        <span className="photo-drop-sub">Front, back, hallmarks, and any certificates. JPG or PNG.</span>
      </button>
      <input ref={inputRef} type="file" accept="image/*" multiple onChange={add} hidden />
      {photos.length > 0 && (
        <div className="photo-thumbs">
          {photos.map((p, i) => (
            <div className="photo-thumb" key={i}>
              <img src={p.url} alt={p.name} />
              <button type="button" className="photo-remove" onClick={() => remove(i)} aria-label="Remove photo"><Icon.X /></button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function Step2({ data, update }) {
  return (
    <>
      <div className="step-title">A few details about the piece.</div>
      <div className="field">
        <label>Photos <span className="req">Required</span></label>
        <PhotoUpload photos={data.photos} update={update} />
      </div>
      <div className="field">
        <label>Brand or maker</label>
        <input
          type="text"
          placeholder="e.g. Rolex, Hermès, Cartier"
          value={data.brand}
          onChange={e => update("brand", e.target.value)}
        />
      </div>
      <div className="field-row">
        <div className="field">
          <label>Model or piece</label>
          <input
            type="text"
            placeholder="e.g. Submariner, Birkin 30"
            value={data.piece}
            onChange={e => update("piece", e.target.value)}
          />
        </div>
        <div className="field">
          <label>Approximate year</label>
          <input
            type="text"
            placeholder="e.g. 2018, vintage"
            value={data.year}
            onChange={e => update("year", e.target.value)}
          />
        </div>
      </div>
      <div className="field">
        <label>Condition or context (optional)</label>
        <textarea
          placeholder="Box and papers? Signs of wear? Anything our team should know."
          value={data.notes}
          onChange={e => update("notes", e.target.value)}
        />
      </div>
    </>
  );
}

function Step3({ data, update }) {
  return (
    <>
      <div className="step-title">Where shall we reach you?</div>
      <div className="step-help">A specialist will respond within one business day. No obligation, no follow-up calls.</div>
      <div className="field-row">
        <div className="field">
          <label>First name</label>
          <input type="text" placeholder="First name" value={data.firstName} onChange={e => update("firstName", e.target.value)} />
        </div>
        <div className="field">
          <label>Last name</label>
          <input type="text" placeholder="Last name" value={data.lastName} onChange={e => update("lastName", e.target.value)} />
        </div>
      </div>
      <div className="field-row">
        <div className="field">
          <label>Email</label>
          <input type="email" placeholder="you@example.com" value={data.email} onChange={e => update("email", e.target.value)} />
        </div>
        <div className="field">
          <label>Phone (optional)</label>
          <input type="tel" placeholder="(310) 555-0000" value={data.phone} onChange={e => update("phone", e.target.value)} />
        </div>
      </div>
    </>
  );
}

// ============================================
// HOW IT WORKS — fullscreen tour
// ============================================
function HowItWorksTour({ open, onClose }) {
  const [idx, setIdx] = useStateMod(0);
  const slides = [
    { num: "01", title: "Submit your piece, in confidence.", body: "Send photographs, or book a private appointment in our Beverly Hills office. There is no fee, and no expectation." },
    { num: "02", title: "A considered appraisal.", body: "Each piece is evaluated by our GIA-certified specialists, with the discretion it deserves. We tell you what we see, and what shapes the offer." },
    { num: "03", title: "A transparent offer.", body: "You receive a market-grounded offer — often the same day. The reasoning is plain. The number reflects current demand, condition, and provenance." },
    { num: "04", title: "Paid on your terms.", body: "Wire, certified check, or in person. Most sellers are paid the day they accept." },
  ];

  useEffectMod(() => {
    if (open) setIdx(0);
  }, [open]);

  useEffectMod(() => {
    function onKey(e) {
      if (!open) return;
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") setIdx(i => Math.min(slides.length - 1, i + 1));
      if (e.key === "ArrowLeft") setIdx(i => Math.max(0, i - 1));
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  useEffectMod(() => {
    document.body.style.overflow = open ? "hidden" : "";
  }, [open]);

  const s = slides[idx];

  return (
    <div className={`tour-backdrop ${open ? "open" : ""}`}>
      <div className="tour-progress">A simple, considered process · {String(idx + 1).padStart(2, "0")} of {String(slides.length).padStart(2, "0")}</div>
      <button className="tour-close" onClick={onClose} aria-label="Close"><Icon.X /></button>

      <div className="tour-card">
        <div className="tour-num" key={s.num}>{s.num}</div>
        <div className="tour-title" key={s.title}>{s.title}</div>
        <div className="tour-body">{s.body}</div>

        <div className="tour-controls">
          <button className="tour-arrow" onClick={() => setIdx(i => Math.max(0, i - 1))} disabled={idx === 0}>
            <Icon.ArrowLeft />
          </button>
          <div className="tour-dots">
            {slides.map((_, i) => <span key={i} className={i === idx ? "active" : ""} />)}
          </div>
          {idx < slides.length - 1 ? (
            <button className="tour-arrow" onClick={() => setIdx(i => i + 1)}>
              <Icon.Arrow size={18} />
            </button>
          ) : (
            <button className="btn btn-gold" onClick={onClose} style={{ marginLeft: 8 }}>
              Get a free valuation
              <Icon.Arrow />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================
// SERVICE REQUEST MODAL
// ============================================
const SERVICES = {
  appraisals: {
    name: "Appraisals",
    title: "Request a formal appraisal.",
    blurb: "Insurance-grade written appraisals for jewelry, watches, and handbags — performed by our GIA-certified specialists.",
    itemLabel: "What would you like appraised?",
    itemPlaceholder: "e.g. 3ct diamond ring, Rolex Daytona",
    notesLabel: "Purpose (optional)",
    notesPlaceholder: "Insurance, estate, resale, or peace of mind…",
    cta: "Request appraisal",
  },
  authentication: {
    name: "Authentication",
    title: "Verify authenticity.",
    blurb: "Independent authentication of watches, handbags, and signed jewelry, with clear documented findings.",
    itemLabel: "What needs authenticating?",
    itemPlaceholder: "e.g. Hermès Birkin, Patek Philippe Nautilus",
    notesLabel: "Anything we should know (optional)",
    notesPlaceholder: "Where it was purchased, papers, prior concerns…",
    cta: "Request authentication",
  },
  "watch-service": {
    name: "Watch Service / Polish",
    title: "Service or polish your watch.",
    blurb: "Cleaning, polishing, movement service, and refinishing for fine timepieces.",
    itemLabel: "Which watch?",
    itemPlaceholder: "e.g. Omega Speedmaster, Cartier Tank",
    notesLabel: "What does it need? (optional)",
    notesPlaceholder: "Polish, full service, crystal, bracelet…",
    cta: "Request service",
  },
  "jewelry-repairs": {
    name: "Jewelry Repairs",
    title: "Repair or restore your jewelry.",
    blurb: "Resizing, stone setting, soldering, clasp and chain repair, and restoration.",
    itemLabel: "What needs repair?",
    itemPlaceholder: "e.g. ring resize, broken clasp, reset stone",
    notesLabel: "Describe the repair (optional)",
    notesPlaceholder: "What happened, ring size, urgency…",
    cta: "Request repair",
  },
};

const EMPTY_SERVICE = { item: "", photos: [], firstName: "", lastName: "", email: "", phone: "", notes: "" };

function ServiceModal({ open, service, onClose }) {
  const cfg = service ? SERVICES[service] : null;
  const [done, setDone] = useStateMod(false);
  const [data, setData] = useStateMod(EMPTY_SERVICE);

  useEffectMod(() => {
    if (open) { setDone(false); setData(EMPTY_SERVICE); }
  }, [open, service]);

  useEffectMod(() => {
    function onKey(e) { if (e.key === "Escape" && open) onClose(); }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  useEffectMod(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  function update(k, v) { setData(d => ({ ...d, [k]: v })); }
  const canSubmit = !!data.item && !!data.firstName && !!data.lastName && !!data.email;

  return (
    <div className={`modal-backdrop ${open ? "open" : ""}`} onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        {cfg && !done && (
          <>
            <div className="modal-header">
              <div>
                <span className="eyebrow">{cfg.name}</span>
                <h3>{cfg.title}</h3>
              </div>
              <button className="modal-close" onClick={onClose} aria-label="Close"><Icon.X /></button>
            </div>
            <div className="modal-body">
              <div className="step-help">{cfg.blurb}</div>
              <div className="field">
                <label>{cfg.itemLabel}</label>
                <input type="text" placeholder={cfg.itemPlaceholder} value={data.item} onChange={e => update("item", e.target.value)} />
              </div>
              <div className="field">
                <label>Photos <span className="opt">Optional</span></label>
                <PhotoUpload photos={data.photos} update={update} />
              </div>
              <div className="field">
                <label>{cfg.notesLabel}</label>
                <textarea placeholder={cfg.notesPlaceholder} value={data.notes} onChange={e => update("notes", e.target.value)} />
              </div>
              <div className="field-row">
                <div className="field">
                  <label>First name</label>
                  <input type="text" placeholder="First name" value={data.firstName} onChange={e => update("firstName", e.target.value)} />
                </div>
                <div className="field">
                  <label>Last name</label>
                  <input type="text" placeholder="Last name" value={data.lastName} onChange={e => update("lastName", e.target.value)} />
                </div>
              </div>
              <div className="field-row">
                <div className="field">
                  <label>Email</label>
                  <input type="email" placeholder="you@example.com" value={data.email} onChange={e => update("email", e.target.value)} />
                </div>
                <div className="field">
                  <label>Phone (optional)</label>
                  <input type="tel" placeholder="Your number" value={data.phone} onChange={e => update("phone", e.target.value)} />
                </div>
              </div>
            </div>
            <div className="modal-footer">
              <button className="secondary" onClick={onClose}>Cancel</button>
              <button
                className="btn btn-gold"
                onClick={() => { if (canSubmit) setDone(true); }}
                style={{ opacity: canSubmit ? 1 : 0.4, pointerEvents: canSubmit ? "auto" : "none" }}
              >
                {cfg.cta}
                <Icon.Arrow />
              </button>
            </div>
          </>
        )}
        {cfg && done && (
          <div className="modal-success">
            <div className="check"><Icon.Check size={28} /></div>
            <h3>Thank you, {data.firstName || "there"}.</h3>
            <p>
              A specialist from our Beverly Hills office will reach out within one business day about your {cfg.name.toLowerCase()} request — by appointment, with full discretion.
            </p>
            <button className="btn btn-outline-navy" onClick={onClose}>Close</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AppraisalModal, ServiceModal, HowItWorksTour });
