// ============================================================
//  MONOGRAM — Bespoke multi-step enquiry flow
// ============================================================

const INTERESTS_EN = [
  { id: "jewellery", title: "Fine", ital: "jewellery.", sub: "Commission a sculptural piece from one of the five collections, or a one-of-a-kind." },
  { id: "invitation", title: "Couture", ital: "invitations.", sub: "Bespoke invitation suite for a wedding, exhibition, or private event." },
  { id: "both", title: "Both —", ital: "a full suite.", sub: "Jewellery + invitations for a single occasion. Treated as one commission." },
  { id: "open", title: "I'd like to", ital: "talk first.", sub: "Not sure yet — book a 30-minute conversation at the d3 studio." },
];
const INTERESTS_AR = [
  { id: "jewellery", title: "مجوهرات", ital: "راقية.", sub: "قطعةٌ نحتيّة من إحدى المجموعات الخمس، أو تصميمٌ فرديّ." },
  { id: "invitation", title: "دعوات", ital: "كوتور.", sub: "دعوات حسب الطلب لعرس، أو معرض، أو مناسبة خاصّة." },
  { id: "both", title: "كلاهما —", ital: "حزمة متكاملة.", sub: "مجوهرات + دعوات لمناسبة واحدة. تُعامَل كطلبٍ واحد." },
  { id: "open", title: "أحبّ", ital: "الحديث أوّلاً.", sub: "لم أحدّد بعد — لقاءٌ مدّته ٣٠ دقيقة في الاستوديو." },
];

const TIMELINE_EN = [
  "Within 1 month",
  "1 – 3 months",
  "3 – 6 months",
  "Open — when the work is ready",
];
const TIMELINE_AR = [
  "خلال شهر",
  "١ – ٣ أشهر",
  "٣ – ٦ أشهر",
  "مفتوح ـ حين يكتمل العمل",
];

function BespokeScreen({ setRoute, locale, preset }) {
  const t = COPY[locale];
  const isAr = locale === "ar";
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    interest: preset || "jewellery",
    collection: preset && preset !== "invitation" ? preset : "sculptural",
    occasion: "",
    timeline: isAr ? TIMELINE_AR[1] : TIMELINE_EN[1],
    refs: [],
    name: "",
    contact: "",
    method: "whatsapp",
    notes: "",
  });
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, []);

  const STEPS = isAr
    ? ["الاهتمام", "التفاصيل", "المراجع", "التواصل", "المراجعة"]
    : ["Interest", "Details", "References", "Contact", "Review"];

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

  // ---- Step renderers ----
  const Step0 = () => (
    <div className="form-step">
      <h2>{isAr ? <>ما الذي يجمعنا <span className="ital">اليوم؟</span></> : <>What brings you <span className="ital">to MONOGRAM?</span></>}</h2>
      <p className="fs-sub">{isAr
        ? "كلّ طلبٍ يبدأ بنوع المشروع. اختر ما يناسبك ـ يمكنك تغييره لاحقاً."
        : "Every commission begins with a kind of project. Pick what fits — you can change this later."}
      </p>
      <div className="opt-grid">
        {(isAr ? INTERESTS_AR : INTERESTS_EN).map((opt) => (
          <button
            key={opt.id}
            className={`opt-card ${data.interest === opt.id ? "selected" : ""}`}
            onClick={() => set("interest", opt.id)}
          >
            <span className="oc-title">{opt.title} <span className="ital">{opt.ital}</span></span>
            <span className="oc-sub">{opt.sub}</span>
          </button>
        ))}
      </div>
    </div>
  );

  const Step1 = () => (
    <div className="form-step">
      <h2>{isAr ? <>التفاصيل <span className="ital">الأوّليّة.</span></> : <>The first <span className="ital">details.</span></>}</h2>
      <p className="fs-sub">{isAr
        ? "كي نأتي إلى اللقاء وفي ذهننا فكرة. كلّ هذه الحقول اختياريّة."
        : "So we arrive at the meeting with something already in mind. All fields are optional."}
      </p>

      {(data.interest === "jewellery" || data.interest === "both") && (
        <div className="fld">
          <label>{isAr ? "المجموعة" : "Collection of interest"}</label>
          <div className="collection-pills">
            {COLLECTIONS.map((c) => (
              <button
                key={c.id}
                className={`coll-pill ${data.collection === c.id ? "selected" : ""}`}
                onClick={() => set("collection", c.id)}
              >
                {isAr ? c.nameAr : c.nameEn}
              </button>
            ))}
            <button
              className={`coll-pill ${data.collection === "open" ? "selected" : ""}`}
              onClick={() => set("collection", "open")}
            >
              {isAr ? "غير محدّد" : "Open / one-of-a-kind"}
            </button>
          </div>
        </div>
      )}

      <div className="fld">
        <label>{isAr ? "المناسبة أو السياق" : "Occasion or context"}</label>
        <input
          type="text"
          value={data.occasion}
          placeholder={isAr ? "عرس، يوم وطني، هديّة شخصيّة..." : "Wedding, national day, personal gift…"}
          onChange={(e) => set("occasion", e.target.value)}
        />
      </div>

      <div className="fld">
        <label>{isAr ? "الجدول الزمنيّ" : "Timeline"}</label>
        <div className="collection-pills">
          {(isAr ? TIMELINE_AR : TIMELINE_EN).map((tl) => (
            <button
              key={tl}
              className={`coll-pill ${data.timeline === tl ? "selected" : ""}`}
              onClick={() => set("timeline", tl)}
            >{tl}</button>
          ))}
        </div>
      </div>
    </div>
  );

  const Step2 = () => {
    const onFile = (e) => {
      const files = Array.from(e.target.files || []).map((f) => f.name);
      set("refs", [...data.refs, ...files]);
    };
    return (
      <div className="form-step">
        <h2>{isAr ? <>المراجع <span className="ital">والإلهام.</span></> : <>References, <span className="ital">if you have any.</span></>}</h2>
        <p className="fs-sub">{isAr
          ? "صورة لحرفٍ تحبّه، ورقةٌ مطويّة، أو ببساطة صورة لقطعة موجودة لديك. اختياريّ."
          : "A letter you love, a folded paper, even a picture of an existing piece you’d like to echo. Optional."}
        </p>

        <label htmlFor="ref-upload" className="drop">
          <div>
            {isAr ? "اضغط لإضافة صور أو اسحبها هنا" : "Click to upload — or drag references here"}
          </div>
          <div style={{ marginTop: 8, color: "var(--muted)", letterSpacing: "0.18em" }}>
            JPG · PNG · PDF · ≤ 10 MB
          </div>
        </label>
        <input id="ref-upload" type="file" multiple accept="image/*,application/pdf" onChange={onFile} style={{ display: "none" }}/>

        {data.refs.length > 0 && (
          <div className="drop-thumbs" aria-live="polite">
            {data.refs.map((r, i) => (
              <div key={i} className="thumb" title={r}>
                {String(i + 1).padStart(2, "0")}
              </div>
            ))}
            <button
              className="coll-pill"
              onClick={() => set("refs", [])}
              style={{ marginInlineStart: 8 }}
            >
              {isAr ? "مسح" : "Clear"}
            </button>
          </div>
        )}

        <div className="fld" style={{ marginTop: 24 }}>
          <label>{isAr ? "ملاحظات للاستوديو" : "Notes for the studio"}</label>
          <textarea
            value={data.notes}
            placeholder={isAr ? "اكتب ما يخطر ببالك ـ الحرف، اللون، الإهداء..." : "Anything that comes to mind — the letter, the colour, the dedication…"}
            onChange={(e) => set("notes", e.target.value)}
          />
        </div>
      </div>
    );
  };

  const Step3 = () => (
    <div className="form-step">
      <h2>{isAr ? <>كيف <span className="ital">نتواصل معك؟</span></> : <>How may we <span className="ital">reach you?</span></>}</h2>
      <p className="fs-sub">{isAr
        ? "نُفضّل واتساب لردٍّ سريع. سيتم تجهيز رسالة مع كلّ ما أدخلته."
        : "We prefer WhatsApp for fastest reply. We’ll pre-fill a message with everything you’ve entered."}
      </p>

      <div className="fld-row">
        <div className="fld">
          <label>{isAr ? "الاسم" : "Name"}</label>
          <input
            type="text"
            placeholder={isAr ? "اسمك" : "Your name"}
            value={data.name}
            onChange={(e) => set("name", e.target.value)}
          />
        </div>
        <div className="fld">
          <label>{isAr ? "البلد / المدينة" : "City"}</label>
          <input
            type="text"
            placeholder={isAr ? "دبي، أبوظبي..." : "Dubai, Abu Dhabi…"}
          />
        </div>
      </div>

      <div className="fld">
        <label>{data.method === "whatsapp" ? "WhatsApp" : (isAr ? "البريد الإلكترونيّ" : "Email")}</label>
        <input
          type="text"
          placeholder={data.method === "whatsapp" ? "+971 50 …" : "you@example.com"}
          value={data.contact}
          onChange={(e) => set("contact", e.target.value)}
        />
      </div>

      <div className="fld">
        <label>{isAr ? "طريقة التواصل المفضّلة" : "Preferred channel"}</label>
        <div className="collection-pills">
          <button className={`coll-pill ${data.method === "whatsapp" ? "selected" : ""}`} onClick={() => set("method", "whatsapp")}>WhatsApp</button>
          <button className={`coll-pill ${data.method === "email" ? "selected" : ""}`} onClick={() => set("method", "email")}>{isAr ? "بريد" : "Email"}</button>
          <button className={`coll-pill ${data.method === "studio" ? "selected" : ""}`} onClick={() => set("method", "studio")}>{isAr ? "زيارة الاستوديو" : "Studio visit"}</button>
        </div>
      </div>
    </div>
  );

  const Step4 = () => {
    const intLabel = (isAr ? INTERESTS_AR : INTERESTS_EN).find((x) => x.id === data.interest);
    const collLabel = COLLECTIONS.find((c) => c.id === data.collection);
    const message =
      (isAr
        ? `مرحباً MONOGRAM،\n\nأودّ بدء استشارة:\n• المشروع: ${intLabel?.title} ${intLabel?.ital}`
        : `Hi MONOGRAM,\n\nI'd like to begin a consultation:\n• Project: ${intLabel?.title} ${intLabel?.ital}`)
      + (data.interest !== "invitation" && collLabel
          ? (isAr ? `\n• المجموعة: ${collLabel.nameAr}` : `\n• Collection: ${collLabel.nameEn}`)
          : "")
      + (data.occasion ? (isAr ? `\n• المناسبة: ${data.occasion}` : `\n• Occasion: ${data.occasion}`) : "")
      + (isAr ? `\n• الجدول: ${data.timeline}` : `\n• Timeline: ${data.timeline}`)
      + (data.refs.length ? (isAr ? `\n• المراجع: ${data.refs.length} ملف(ات)` : `\n• References: ${data.refs.length} file(s)`) : "")
      + (data.notes ? (isAr ? `\n• ملاحظات: ${data.notes}` : `\n• Notes: ${data.notes}`) : "")
      + (data.name ? (isAr ? `\n\n— ${data.name}` : `\n\n— ${data.name}`) : "");

    const waHref = "https://wa.me/971504563365?text=" + encodeURIComponent(message);

    return (
      <div className="form-step">
        <h2>{isAr ? <>المراجعة <span className="ital">الأخيرة.</span></> : <>One last <span className="ital">look.</span></>}</h2>
        <p className="fs-sub">{isAr
          ? "هذه الرسالة جاهزة للإرسال على واتساب. يمكنك تعديلها قبل الإرسال."
          : "This message is ready to send on WhatsApp. You can adjust it before sending."}
        </p>

        <div className="wa-preview">
          <div className="wa-head">
            <span className="wa-label">{isAr ? "إلى MONOGRAM" : "Message to MONOGRAM"}</span>
            <span className="wa-num">+971 50 456 3365</span>
          </div>
          <div className="wa-msg">{message}</div>
        </div>

        <div style={{ display: "flex", gap: 12, marginTop: 24, flexWrap: "wrap" }}>
          <a
            className="btn solid"
            href={waHref}
            target="_blank"
            rel="noopener noreferrer"
            onClick={() => { setTimeout(() => setSubmitted(true), 500); }}
          >
            <span>{isAr ? "أرسل عبر واتساب" : "Send via WhatsApp"}</span>
            <span className="arrow">→</span>
          </a>
          <button className="btn ghost" onClick={() => setSubmitted(true)}>
            <span>{isAr ? "أرسل وأكتفي بالبريد" : "Send & email me instead"}</span>
          </button>
        </div>

        <p style={{
          marginTop: 24,
          fontFamily: "var(--font-mono)",
          fontSize: 11,
          letterSpacing: "0.2em",
          textTransform: "uppercase",
          color: "var(--muted)",
        }}>
          {isAr
            ? "نموذج تفاعليّ ـ لا يُرسَل البريد فعليًّا في هذا العرض."
            : "Prototype · the email path is mocked, the WhatsApp link is live."}
        </p>
      </div>
    );
  };

  const stepBody = [Step0, Step1, Step2, Step3, Step4][step];

  if (submitted) {
    return (
      <main className="wrap" style={{ minHeight: "100vh", paddingTop: 140 }}>
        <div className="bespoke-right" style={{ maxWidth: 720, margin: "0 auto" }}>
          <div className="success-state">
            <div className="ss-mark">✓</div>
            <h2>{isAr ? <>اللقاء <span className="ital">قد بدأ.</span></> : <>The conversation <span className="ital">has begun.</span></>}</h2>
            <p>{isAr
              ? "شكراً. سيتواصل معك أحد المصمّمين خلال يوم العمل التالي. في هذه الأثناء يمكنك متابعتنا على إنستغرام، أو زيارتنا في الاستوديو بموعد مسبق."
              : "Thank you. A designer from the studio will be in touch within one business day. In the meantime you can follow on Instagram, or visit the studio by appointment."}
            </p>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
              <button className="btn solid" onClick={() => setRoute({ name: "home" })}>
                <span>{isAr ? "العودة إلى الرئيسية" : "Back to home"}</span>
              </button>
              <a className="btn ghost" href="https://instagram.com/monogramuae" target="_blank" rel="noopener noreferrer">
                <span>@monogramuae</span>
              </a>
            </div>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="wrap bespoke-shell">
      <aside className="bespoke-left">
        <div className="bl-eyebrow">{isAr ? "حسب الطلب" : "Bespoke"}</div>
        <h1>
          {isAr
            ? <>ابدأ <span className="ital">قطعتك.</span></>
            : <>Begin a <span className="ital">commission.</span></>
          }
        </h1>
        <p>{isAr
          ? "في MONOGRAM، تبدأ كلّ قطعة بحوار. هذا النموذج يجمع التفاصيل الأوّليّة، ثمّ يفتح واتساب برسالةٍ جاهزة."
          : "At MONOGRAM, every piece begins with a conversation. This form gathers the first details, then opens WhatsApp with a ready message."}
        </p>
        <p>{isAr
          ? "تستغرق العمليّة من ٣ دقائق إلى ٥. لا يُحفظ شيء على خادم خارجيّ."
          : "Takes three to five minutes. Nothing is stored on a third-party server."}
        </p>

        <div className="step-list" aria-label="progress">
          {STEPS.map((label, i) => (
            <div
              key={i}
              className={"step-row " + (i === step ? "active" : i < step ? "done" : "")}
            >
              <span className="step-num">{String(i + 1).padStart(2, "0")}</span>
              <span>{label}</span>
            </div>
          ))}
        </div>

        <div style={{ marginTop: 28, fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase", color: "var(--muted)", lineHeight: 1.7 }}>
          {isAr ? "أو ـ تواصل مباشر" : "Or — direct channel"}<br/>
          <a href="https://wa.me/971504563365" target="_blank" rel="noopener noreferrer" style={{ color: "var(--primary)" }}>
            WhatsApp · +971 50 456 3365
          </a>
        </div>
      </aside>

      <section className="bespoke-right" aria-live="polite">
        {stepBody()}
        <div className="form-nav">
          <div className="left-side">
            {step > 0 && (
              <button className="btn ghost" onClick={() => setStep((s) => Math.max(0, s - 1))}>
                <span>{isAr ? "السابق" : "Back"}</span>
              </button>
            )}
            <button className="btn ghost" onClick={() => setRoute({ name: "home" })}>
              <span>{isAr ? "إلغاء" : "Cancel"}</span>
            </button>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
            <span className="progress">
              {String(step + 1).padStart(2, "0")} / {String(STEPS.length).padStart(2, "0")}
            </span>
            {step < STEPS.length - 1 && (
              <button className="btn solid" onClick={() => setStep((s) => Math.min(STEPS.length - 1, s + 1))}>
                <span>{isAr ? "التالي" : "Continue"}</span>
                <span className="arrow">→</span>
              </button>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { BespokeScreen });
