// StompGear — Step 2: AI Generation Loading Screen

async function generateListing(inputs) {
  if (!window.claude) return DEMO_LISTING;
  try {
    const hasUrl = inputs.url && inputs.url.trim().length > 5;
    const hasDetails = inputs.details && inputs.details.trim().length > 2;
    if (!hasUrl && !hasDetails) return DEMO_LISTING;

    const prompt = `You are an AI assistant for StompGear, a Canadian outdoor gear rental marketplace (stompgear.ca) in the Kootenays, BC.

Owner inputs:
${hasUrl ? `Product URL: ${inputs.url}` : ""}
${hasDetails ? `Owner notes: ${inputs.details}` : ""}
${inputs.category ? `Category hint: ${inputs.category}` : ""}

Generate a rental listing JSON object. Return ONLY valid JSON, no markdown, no explanation.

{
  "title": "Brand Model — Key Feature (e.g. Trek Fuel EX 9.7 Full-Suspension Mountain Bike)",
  "category": "Cycling",
  "subcategory": "specific subcategory",
  "brand": "brand name",
  "model": "model name",
  "year": null,
  "capacity": "e.g. 3-5 persons or dimensions",
  "description": "2 short paragraphs in friendly owner tone, written for renters. Highlight what makes it great, local context if applicable.",
  "accessories": ["item1", "item2", "item3"],
  "retailValue": 1500,
  "dailyRate": 75,
  "weeklyRate": 375,
  "deposit": 300,
  "rules": "safety rules for this gear category, 1-2 sentences",
  "confidence": {
    "title": "high",
    "description": "high",
    "accessories": "medium",
    "dailyRate": "medium",
    "deposit": "medium",
    "year": "low"
  }
}`;

    const response = await window.claude.complete(prompt);
    const match = response.match(/\{[\s\S]*\}/);
    if (!match) throw new Error("No JSON");
    const ai = JSON.parse(match[0]);
    return {
      ...DEMO_LISTING,
      ...ai,
      condition: null,
      photos: DEMO_LISTING.photos,
      location: "Kimberley, BC",
      pickupAddress: "310 Spokane St, Kimberley, BC",
      ownerName: "Chris M.",
      ownerJoined: "2021",
      ownerListings: 4
    };
  } catch (e) {
    console.warn("AI generation failed, using demo:", e);
    return DEMO_LISTING;
  }
}

function Step2({ inputs, onDone }) {
  const [progress, setProgress] = React.useState(0);

  const steps = [
    { label: "Reading your image…",            ms: 500  },
    { label: "Looking up the product…",        ms: 1100 },
    { label: "Drafting the description…",      ms: 1900 },
    { label: "Suggesting pricing & rules…",    ms: 2700 },
    { label: "Putting it all together…",       ms: 3400 }
  ];

  React.useEffect(() => {
    steps.forEach((s, i) => {
      setTimeout(() => setProgress(i + 1), s.ms);
    });
    let done = false;
    setTimeout(async () => {
      if (done) return;
      done = true;
      const listing = await generateListing(inputs);
      onDone(listing);
    }, 4200);
  }, []);

  return (
    <div style={{ minHeight: "100vh", background: "#F7F8F9", display: "flex", flexDirection: "column" }}>

      {/* Topbar */}
      <header style={{ background: "#fff", height: 60, display: "flex", alignItems: "center", justifyContent: "space-between", padding: "0 16px", boxShadow: "0 1px 0 #f0f0f0", position: "sticky", top: 0, zIndex: 50 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <StompLogo size={22} />
          <span style={{ fontFamily: "'Montserrat', sans-serif", fontWeight: 700, fontSize: 17, letterSpacing: "0.05em" }}>STOMP<span style={{ color: "#015672" }}>GEAR</span></span>
        </div>
      </header>

      {/* Step progress */}
      <div style={{ background: "#fff", padding: "10px 16px 12px", borderBottom: "1px solid #ececec" }}>
        <div style={{ display: "flex", alignItems: "center", maxWidth: 400, marginBottom: 8 }}>
          {[{ n: 1 }, { n: 2 }, { n: 3 }].map((s, i, arr) => (
            <React.Fragment key={s.n}>
              <div style={{ width: 26, height: 26, borderRadius: "50%", background: s.n <= 2 ? "#015672" : "#e5e7eb", color: s.n <= 2 ? "#fff" : "#9ca3af", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700, fontFamily: "'Inter', sans-serif", flexShrink: 0 }}>
                {s.n === 1 ? <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3"><path d="M20 6L9 17l-5-5" /></svg> : s.n}
              </div>
              {i < arr.length - 1 && <div style={{ flex: 1, height: 2, background: s.n === 1 ? "#015672" : "#e5e7eb", margin: "0 6px" }} />}
            </React.Fragment>
          ))}
        </div>
        <div style={{ fontSize: 11, color: "#6b7280", fontFamily: "'Inter', sans-serif" }}>Step 2 of 3 — Building your listing</div>
      </div>

      {/* Content */}
      <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: "32px 24px" }}>
        <div style={{ maxWidth: 380, width: "100%" }}>

          {/* Icon */}
          <div style={{ display: "flex", justifyContent: "center", marginBottom: 28 }}>
            <div style={{ width: 72, height: 72, borderRadius: "50%", background: "#015672", display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 0 0 10px rgba(1,86,114,0.08), 0 0 0 20px rgba(1,86,114,0.04)" }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.5">
                <path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
              </svg>
            </div>
          </div>

          <h2 style={{ fontFamily: "'Poppins', sans-serif", fontWeight: 600, fontSize: 20, color: "#111827", textAlign: "center", marginBottom: 6 }}>
            We're filling this in for you
          </h2>
          <p style={{ fontSize: 13, color: "#6b7280", fontFamily: "'Inter', sans-serif", textAlign: "center", marginBottom: 28, lineHeight: 1.65 }}>
            Based on what you shared, we're building a complete draft listing. You'll review and adjust everything before it goes live.
          </p>

          {/* Step checklist */}
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {steps.map((step, i) => {
              const done = progress > i;
              const active = progress === i && progress < steps.length;
              return (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", borderRadius: 8, background: done ? "#f0fff6" : active ? "#fff" : "#fafafa", border: `1px solid ${done ? "#bbf7d0" : active ? "#e5e7eb" : "#f3f4f6"}`, transition: "all 0.4s ease", opacity: progress < i ? 0.35 : 1 }}>
                  <div style={{ width: 22, height: 22, borderRadius: "50%", flexShrink: 0, background: done ? "#16a34a" : active ? "#015672" : "#e5e7eb", display: "flex", alignItems: "center", justifyContent: "center", transition: "background 0.3s" }}>
                    {done ? (
                      <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3.5"><path d="M20 6L9 17l-5-5" /></svg>
                    ) : active ? (
                      <div style={{ width: 7, height: 7, borderRadius: "50%", background: "white", animation: "sgPulse 1s ease-in-out infinite" }} />
                    ) : null}
                  </div>
                  <span style={{ fontSize: 13, fontFamily: "'Inter', sans-serif", fontWeight: done ? 500 : 400, color: done ? "#15803d" : active ? "#111827" : "#9ca3af", transition: "color 0.3s" }}>
                    {step.label}
                  </span>
                </div>
              );
            })}
          </div>

          {/* Progress bar */}
          <div style={{ marginTop: 20, height: 4, background: "#e5e7eb", borderRadius: 2, overflow: "hidden" }}>
            <div style={{ height: "100%", background: "#015672", borderRadius: 2, width: `${(progress / steps.length) * 100}%`, transition: "width 0.5s ease" }} />
          </div>
        </div>
      </div>

      <style>{`
        @keyframes sgPulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(0.8); } }
      `}</style>
    </div>
  );
}

Object.assign(window, { Step2, generateListing });
