/* Interactive Walkthrough — guided tour of the Rate Services portal */
const { useState } = React;

function Walkthrough({ onBack }) {
  const T = window.EMMA_TOKENS;
  const [slide, setSlide] = useState(0);

  const slides = [
    // 0: Welcome
    {
      section: "Welcome",
      title: "Rate Services Portal",
      subtitle: "Interactive Guide",
      content: (
        <div style={{ textAlign: "center", padding: "30px 0" }}>
          <div style={{ width: 72, height: 72, borderRadius: "50%", background: T.accentSoft, display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 20 }}>
            <svg width="32" height="32" viewBox="0 0 32 32" fill="none"><path d="M16 4v24M4 16h24" stroke={T.accent} strokeWidth="2.5" strokeLinecap="round"/></svg>
          </div>
          <p style={{ fontSize: 15, color: T.ink, lineHeight: 1.7, maxWidth: 480, margin: "0 auto" }}>
            This guide walks you through each form on the portal. Use the <strong>Next</strong> and <strong>Back</strong> buttons to navigate, or click any section in the sidebar.
          </p>
          <div style={{ display: "flex", gap: 12, justifyContent: "center", marginTop: 30 }}>
            <Chip color="#0E5E55" label="New Rate Request" />
            <Chip color="#5B6E4E" label="Update Existing Rate" />
            <Chip color="#6B5B3E" label="General Request" />
          </div>
        </div>
      ),
    },
    // 1: Landing Page
    {
      section: "Overview",
      title: "The Landing Page",
      subtitle: "Your starting point",
      content: (
        <div>
          <StepVisual
            number="—"
            title="Three tiles to choose from"
            items={[
              { label: "New Rate Request", desc: "Full wizard for loading a brand new rate — pricing, seasons, contract, stay rules" },
              { label: "Update Existing Rate", desc: "Modify pricing, extend dates, or update terms on a rate already in the system" },
              { label: "General Request", desc: "Questions, issues, or anything not covered by the other two forms" },
            ]}
          />
          <InfoBox>Standard processing time is 5 business days. GDS requests can take up to 5 additional days. Lanyon RFPs do not require a submission.</InfoBox>
        </div>
      ),
    },
    // 2: New Rate — Requester
    {
      section: "New Rate",
      title: "Step 1: Requester",
      subtitle: "Who is filing this request",
      content: (
        <div>
          <StepVisual
            number="1"
            title="Your details"
            items={[
              { label: "Your name", desc: "Full name — this is who the ticket is assigned to" },
              { label: "Email", desc: "Your Axiom email — confirmation will be sent here" },
            ]}
          />
          <InfoBox>You'll see processing time notes and important reminders about new accounts, GDS, and peak RFP season on this step.</InfoBox>
        </div>
      ),
    },
    // 3: New Rate — Identify Client
    {
      section: "New Rate",
      title: "Step 2: Identify Client",
      subtitle: "Customer, hotels & channels",
      content: (
        <div>
          <StepVisual
            number="2"
            title="Client details"
            items={[
              { label: "Customer status", desc: "Existing or New — new accounts require a database profile first" },
              { label: "Customer details", desc: "Name, address, email, phone, and one or more Customer IDs (PCR, IATA, or Emma Client ID)" },
              { label: "Hotels in scope", desc: "Select all hotels this rate applies to — required before pricing" },
              { label: "Channels", desc: "Hotel Direct, Hotel Website, and/or GDS" },
              { label: "Reason for request", desc: "Why this rate is being loaded (renewal, RFP win, amendment, etc.)" },
            ]}
          />
          <WarningBox>If <strong>GDS</strong> is selected, you'll be asked whether the RFP is managed in Lanyon, and reminded to upload GDS loading instructions in the Files step.</WarningBox>
        </div>
      ),
    },
    // 4: New Rate — Price Code
    {
      section: "New Rate",
      title: "Step 3: Price Code",
      subtitle: "Room types, meals & pricing",
      content: (
        <div>
          <StepVisual
            number="3"
            title="Pricing setup"
            items={[
              { label: "Pricing type", desc: "Dynamic Rate (% discount off a base rate) or Static Rate (fixed amounts)" },
              { label: "Room types", desc: "Free text — add up to 8 (e.g. Standard Double, Superior King)" },
              { label: "Meal plans", desc: "Room Only and/or Bed & Breakfast" },
              { label: "Seasons", desc: "Add date ranges with pricing. Use + Add season for more." },
            ]}
          />
          <div style={{ display: "flex", gap: 12, marginTop: 16 }}>
            <MiniCard title="Dynamic Rate" color="#0E5E55" items={["Based on rate (free text)", "% discount (e.g. -10%)", "Days of week filter", "Same dates, different days = midweek/weekend split"]} />
            <MiniCard title="Static Rate" color="#5B6E4E" items={["Pricing grid per season", "1AD and 2AD are mandatory *", "Empty cells highlighted red", "Each hotel gets its own grid"]} />
          </div>
        </div>
      ),
    },
    // 5: New Rate — Rate
    {
      section: "New Rate",
      title: "Step 4: Rate",
      subtitle: "Windows, inclusions & segment",
      content: (
        <div>
          <StepVisual
            number="4"
            title="Rate details"
            items={[
              { label: "Booking & stay windows", desc: "When bookings can be made and when guests can stay. Use 'Copy from price code' to auto-fill." },
              { label: "Rate name / description", desc: "Visible to bookers — describe what this rate offers" },
              { label: "Inclusions", desc: "What's included (WiFi, breakfast, late checkout, etc.)" },
              { label: "Market segment", desc: "Corporate, Crew & Layovers, Tour Operator, Flexible, etc." },
            ]}
          />
        </div>
      ),
    },
    // 6: New Rate — Contract
    {
      section: "New Rate",
      title: "Step 5: Contract",
      subtitle: "Validity, cancellation & stay rules",
      content: (
        <div>
          <StepVisual
            number="5"
            title="Contract terms"
            items={[
              { label: "Rate type", desc: "Corporate Negotiated, Group, Wholesale, etc. If Corporate Negotiated, select LRA type." },
              { label: "Validity dates", desc: "Contract start and end dates" },
              { label: "Currency & tax", desc: "Defaults to GBP. Inclusive or Exclusive tax handling." },
              { label: "Cancellation policy", desc: "Free text — describe the full cancellation terms" },
              { label: "Stay rules", desc: "Min/max length of stay, blackout dates, day-of-week restrictions, advance purchase, commission %" },
            ]}
          />
        </div>
      ),
    },
    // 7: New Rate — Files & Review
    {
      section: "New Rate",
      title: "Steps 6 & 7: Files & Review",
      subtitle: "Upload documents and submit",
      content: (
        <div>
          <StepVisual
            number="6"
            title="Files"
            items={[
              { label: "Attachments", desc: "Upload rate sheets, signed contracts, GDS instructions" },
              { label: "Notes", desc: "Anything else for the load team" },
            ]}
          />
          <div style={{ height: 1, background: T.border, margin: "16px 0" }} />
          <StepVisual
            number="7"
            title="Review & Submit"
            items={[
              { label: "Review all sections", desc: "Every field is shown for final check. Click 'Edit step X' to go back." },
              { label: "Confirm & submit", desc: "Tick the confirmation checkbox, then click Submit. A Freshdesk ticket is created with all details and attachments." },
            ]}
          />
          <InfoBox>After submission, you'll see a reference number (e.g. RLR-20260520-A3X7K). The load team is notified automatically.</InfoBox>
        </div>
      ),
    },
    // 8: Update Existing Rate
    {
      section: "Update Rate",
      title: "Update Existing Rate",
      subtitle: "Tile 2 — modify a loaded rate",
      content: (
        <div>
          <StepVisual
            number="2"
            title="Single-page form"
            items={[
              { label: "Requester", desc: "Your name and email" },
              { label: "Current rate", desc: "Customer name, Customer IDs (PCR/IATA/Emma), hotels, channels, rate reference, reason for update" },
              { label: "Updated pricing", desc: "Same Dynamic/Static pricing as Tile 1 — room types, meals, seasons" },
              { label: "Files & notes", desc: "Upload supporting documents" },
            ]}
          />
          <WarningBox>Rates entered will <strong>override</strong> current pricing seasons. Only use applicable date ranges.</WarningBox>
        </div>
      ),
    },
    // 9: General Request
    {
      section: "General",
      title: "General Request",
      subtitle: "Tile 3 — questions & ad-hoc",
      content: (
        <div>
          <StepVisual
            number="3"
            title="Simple form"
            items={[
              { label: "Requester", desc: "Your name and email" },
              { label: "Hotels", desc: "Which hotels this relates to" },
              { label: "Subject & message", desc: "Describe what you need in full detail" },
              { label: "Attachments", desc: "Optional supporting documents" },
            ]}
          />
          <InfoBox>Use this for anything not covered by the rate request forms: questions, amendments, issues, or ad-hoc requests.</InfoBox>
        </div>
      ),
    },
    // 10: Tips
    {
      section: "Tips",
      title: "Tips & Key Points",
      subtitle: "Things to remember",
      content: (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <TipCard icon="🏨" title="Hotels first" desc="You must select hotels on the Identify Client step before the Price Code step unlocks." />
          <TipCard icon="📅" title="Season overlaps" desc="The form warns you if seasons overlap on the same dates and days. Adjust ranges to fix." />
          <TipCard icon="📎" title="Real files only" desc="Upload actual files through the picker. 'Fill sample' creates fake metadata that won't attach." />
          <TipCard icon="🔙" title="Navigation" desc="Browser back button works. There's also a 'Back to home' link in the sidebar." />
          <TipCard icon="✅" title="Mandatory fields" desc="Fields with * are required. For Static Rate, 1AD and 2AD amounts must be filled." />
          <TipCard icon="🌐" title="GDS" desc="Allow 5 extra days. Upload GDS loading instructions. Answer the Lanyon question." />
        </div>
      ),
    },
  ];

  const cur = slides[slide];
  const sections = [...new Set(slides.map(s => s.section))];

  return (
    <div style={{ minHeight: "100vh", background: T.bg, fontFamily: "'Inter', system-ui, sans-serif" }}>
      <div style={{ maxWidth: 1000, margin: "0 auto", display: "grid", gridTemplateColumns: "220px 1fr", minHeight: "100vh" }}>
        {/* Sidebar */}
        <aside style={{ borderRight: `1px solid ${T.border}`, background: T.surface, padding: "24px 0" }}>
          <button type="button" onClick={onBack} style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 20px 16px", background: "transparent", border: "none", color: T.accent, fontSize: 12.5, fontWeight: 600, cursor: "pointer", width: "100%", borderBottom: `1px solid ${T.border}`, marginBottom: 12 }}>
            ← Back to portal
          </button>
          <div style={{ padding: "0 20px 10px", fontSize: 10, fontWeight: 700, color: T.faint, letterSpacing: 1, textTransform: "uppercase" }}>Guide</div>
          {slides.map((s, i) => {
            const active = i === slide;
            const isNewSection = i === 0 || slides[i - 1].section !== s.section;
            return (
              <div key={i}>
                {isNewSection && i > 0 && <div style={{ height: 1, background: T.border, margin: "8px 16px" }} />}
                <button onClick={() => setSlide(i)} style={{
                  display: "block", width: "100%", padding: "8px 20px", border: "none", textAlign: "left", cursor: "pointer",
                  background: active ? T.accentSoft : "transparent",
                  borderLeft: `3px solid ${active ? T.accent : "transparent"}`,
                }}>
                  <div style={{ fontSize: 12.5, fontWeight: active ? 600 : 500, color: active ? T.accentInk : T.ink }}>{s.title}</div>
                </button>
              </div>
            );
          })}
        </aside>

        {/* Content */}
        <main style={{ padding: "32px 40px", overflowY: "auto" }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: T.faint, letterSpacing: 1, textTransform: "uppercase", marginBottom: 6 }}>{cur.section}</div>
          <h1 style={{ margin: "0 0 4px", fontSize: 28, fontWeight: 500, color: T.ink, fontFamily: "'Cormorant Garamond', Georgia, serif" }}>{cur.title}</h1>
          <p style={{ margin: "0 0 24px", fontSize: 13, color: T.muted }}>{cur.subtitle}</p>
          {cur.content}

          {/* Navigation */}
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 32, paddingTop: 20, borderTop: `1px solid ${T.border}` }}>
            <button onClick={() => setSlide(Math.max(0, slide - 1))} disabled={slide === 0} style={{
              padding: "10px 20px", borderRadius: 6, border: `1px solid ${T.border}`, background: T.surface,
              color: slide === 0 ? T.faint : T.ink, cursor: slide === 0 ? "default" : "pointer", fontSize: 13, fontWeight: 500,
            }}>← Previous</button>
            <span style={{ fontSize: 12, color: T.muted }}>{slide + 1} / {slides.length}</span>
            {slide < slides.length - 1 ? (
              <button onClick={() => setSlide(slide + 1)} style={{
                padding: "10px 20px", borderRadius: 6, border: "none", background: T.accent, color: "#fff",
                cursor: "pointer", fontSize: 13, fontWeight: 600,
              }}>Next →</button>
            ) : (
              <button onClick={onBack} style={{
                padding: "10px 20px", borderRadius: 6, border: "none", background: T.accent, color: "#fff",
                cursor: "pointer", fontSize: 13, fontWeight: 600,
              }}>Go to portal →</button>
            )}
          </div>
        </main>
      </div>
    </div>
  );
}

// Helper components
function Chip({ color, label }) {
  const T = window.EMMA_TOKENS;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 6, background: `${color}10`, border: `1px solid ${color}30`, fontSize: 13, fontWeight: 600, color }}>
      <span style={{ width: 8, height: 8, borderRadius: "50%", background: color }} />
      {label}
    </span>
  );
}

function StepVisual({ number, title, items }) {
  const T = window.EMMA_TOKENS;
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
        <div style={{ width: 28, height: 28, borderRadius: "50%", background: T.accent, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 700 }}>{number}</div>
        <div style={{ fontSize: 15, fontWeight: 600, color: T.ink }}>{title}</div>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginLeft: 38 }}>
        {items.map((item, i) => (
          <div key={i} style={{ display: "flex", gap: 10, padding: "8px 12px", background: T.surface, border: `1px solid ${T.border}`, borderRadius: 6 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: T.accent, minWidth: 140 }}>{item.label}</div>
            <div style={{ fontSize: 12.5, color: T.muted, lineHeight: 1.5 }}>{item.desc}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function InfoBox({ children }) {
  const T = window.EMMA_TOKENS;
  return (
    <div style={{ marginTop: 16, padding: "12px 16px", background: T.accentSoft, border: `1px solid ${T.accent}30`, borderRadius: 6, fontSize: 12.5, color: T.accentInk, lineHeight: 1.6 }}>
      <strong>💡 </strong>{children}
    </div>
  );
}

function WarningBox({ children }) {
  return (
    <div style={{ marginTop: 16, padding: "12px 16px", background: "#FBF1D9", border: "1px solid #E2C77E", borderRadius: 6, fontSize: 12.5, color: "#7A5A0B", lineHeight: 1.6 }}>
      <strong>⚠️ </strong><span dangerouslySetInnerHTML={{ __html: typeof children === "string" ? children : "" }} />{typeof children !== "string" && children}
    </div>
  );
}

function MiniCard({ title, color, items }) {
  const T = window.EMMA_TOKENS;
  return (
    <div style={{ flex: 1, border: `1px solid ${color}40`, borderRadius: 8, overflow: "hidden" }}>
      <div style={{ padding: "8px 12px", background: `${color}10`, borderBottom: `1px solid ${color}30` }}>
        <div style={{ fontSize: 13, fontWeight: 700, color }}>{title}</div>
      </div>
      <div style={{ padding: "10px 12px" }}>
        {items.map((item, i) => (
          <div key={i} style={{ fontSize: 11.5, color: T.muted, lineHeight: 1.6, paddingLeft: 10, position: "relative" }}>
            <span style={{ position: "absolute", left: 0 }}>•</span>{item}
          </div>
        ))}
      </div>
    </div>
  );
}

function TipCard({ icon, title, desc }) {
  const T = window.EMMA_TOKENS;
  return (
    <div style={{ display: "flex", gap: 14, padding: "14px 16px", background: T.surface, border: `1px solid ${T.border}`, borderRadius: 8 }}>
      <div style={{ fontSize: 22, lineHeight: 1 }}>{icon}</div>
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: T.ink, marginBottom: 3 }}>{title}</div>
        <div style={{ fontSize: 12.5, color: T.muted, lineHeight: 1.5 }}>{desc}</div>
      </div>
    </div>
  );
}

window.Walkthrough = Walkthrough;
