/* Mereka v2 — Onboarding flows */

function OnboardingShell({ steps, current, title, children, back, next, side }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <header className="bg-white border-b border-neutral-200">
        <div className="max-w-[min(1800px,90vw)] mx-auto px-6 h-16 flex items-center justify-between">
          <Link to="/web" aria-label="Mereka">
            <div style={{ height: 32 }}><MerekaLogo /></div>
          </Link>
          <Link to="/app/dashboard/overview" className="text-sm text-neutral-500 hover:text-neutral-900 inline-flex items-center gap-1">
            Save &amp; exit <Icon name="close" size={14} />
          </Link>
        </div>
        <div className="max-w-[min(1800px,90vw)] mx-auto px-6 pb-3">
          <div className="flex items-center gap-2">
            {steps.map((s, i) => (
              <React.Fragment key={s}>
                <div className={`flex items-center gap-2 ${i <= current ? 'text-neutral-900' : 'text-neutral-400'}`}>
                  <div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-semibold ${i < current ? 'bg-neutral-900 text-white' : i === current ? 'border-2 border-neutral-900 bg-white' : 'border-2 border-neutral-200 bg-white'}`}>
                    {i < current ? <Icon name="check" size={12} /> : i + 1}
                  </div>
                  <span className="hidden md:inline text-xs font-medium">{s}</span>
                </div>
                {i < steps.length - 1 && <div className={`flex-1 h-px ${i < current ? 'bg-neutral-900' : 'bg-neutral-200'}`} />}
              </React.Fragment>
            ))}
          </div>
        </div>
      </header>

      <main className="max-w-[min(1800px,90vw)] mx-auto px-6 py-10">
        <div className="grid lg:grid-cols-[1fr_320px] gap-8">
          <div>
            <h1 className="text-2xl lg:text-3xl font-bold mb-6">{title}</h1>
            {children}
            <div className="flex items-center justify-between mt-10 pt-6 border-t border-neutral-200">
              <Link to={back || '#'} className="text-sm text-neutral-500 hover:text-neutral-900 inline-flex items-center gap-1">
                <Icon name="chevronLeft" size={14} /> Back
              </Link>
              <Link to={next || '#'}>
                <Button variant="primary" size="lg" rightIcon="arrowRight">Continue</Button>
              </Link>
            </div>
          </div>
          {side && <aside className="hidden lg:block">{side}</aside>}
        </div>
      </main>
    </div>
  );
}

function TipsCard({ title = 'Tips', items }) {
  return (
    <Card className="bg-primary text-white !border-primary sticky top-6">
      <div className="flex items-center gap-2 mb-3">
        <Icon name="spark" size={16} className="text-amber-300" />
        <h3 className="font-semibold">{title}</h3>
      </div>
      <ul className="space-y-3 text-sm text-white/80">
        {items.map(i => (
          <li key={i} className="flex items-start gap-2">
            <Icon name="check" size={14} className="text-green-400 mt-0.5 flex-shrink-0" /> {i}
          </li>
        ))}
      </ul>
    </Card>
  );
}

/* ============ WELCOME (universal) ============ */
function OnboardingWelcomePage({ type = 'hub' }) {
  const config = {
    hub: {
      title: 'List your hub on Mereka',
      sub: 'Reach 4,200+ clients across SEA. We handle bookings, payouts and reviews.',
      icon: 'building',
      perks: [
        { t: 'Bookings & payouts in one place', d: 'Schedule, payment processing, refunds and tax — all handled.' },
        { t: 'Built-in trust', d: 'Verified clients, identity checks and our resolution centre.' },
        { t: 'Hub Pro tools', d: 'Team roles, calendars, analytics and programs.' },
      ],
      next: '/app/onboarding/hub/profile',
    },
    expert: {
      title: 'Become an Expert on Mereka',
      sub: 'Find vetted clients, ship great work, and grow a portfolio that pays.',
      icon: 'award',
      perks: [
        { t: 'Vetted briefs only', d: 'No fishing for leads. Real budgets, real timelines.' },
        { t: 'Milestone-based contracts', d: 'Funds held in escrow. You get paid on milestone delivery.' },
        { t: 'Build your practice', d: 'Reviews become reputation. Reputation becomes pricing power.' },
      ],
      next: '/app/onboarding/expert/profile',
    },
    learner: {
      title: 'Welcome to Mereka',
      sub: "Let's set up your account so we can recommend experiences and experts you'll love.",
      icon: 'compass',
      perks: [
        { t: 'Personalised recommendations', d: 'Based on your interests, location and goals.' },
        { t: 'All your bookings, one inbox', d: 'Workshops, sessions and programs in one feed.' },
        { t: 'Skills that compound', d: 'Track progress, earn certificates, build a portfolio.' },
      ],
      next: '/app/onboarding/learner/interests',
    },
  };
  const c = config[type];
  return (
    <div className="min-h-screen bg-neutral-50">
      <header className="bg-white border-b border-neutral-200">
        <div className="max-w-[min(1800px,90vw)] mx-auto px-6 h-16 flex items-center justify-between">
          <Link to="/web" aria-label="Mereka"><div style={{ height: 32 }}><MerekaLogo /></div></Link>
          <Link to="/app/dashboard/overview" className="text-sm text-neutral-500 hover:text-neutral-900">Maybe later</Link>
        </div>
      </header>
      <main className="max-w-3xl mx-auto px-6 py-16 text-center">
        <div className="w-20 h-20 rounded-2xl bg-primary text-white mx-auto flex items-center justify-center mb-6">
          <Icon name={c.icon} size={36} />
        </div>
        <h1 className="text-3xl lg:text-5xl font-bold tracking-tight">{c.title}</h1>
        <p className="text-lg text-neutral-600 mt-4 max-w-2xl mx-auto">{c.sub}</p>

        <div className="mt-12 grid md:grid-cols-3 gap-4 text-left">
          {c.perks.map((p, i) => (
            <Card key={i}>
              <div className="w-10 h-10 rounded-xl bg-primary/10 text-primary flex items-center justify-center mb-3">
                <span className="font-bold">{i + 1}</span>
              </div>
              <h3 className="font-semibold mb-1">{p.t}</h3>
              <p className="text-sm text-neutral-600">{p.d}</p>
            </Card>
          ))}
        </div>

        <div className="mt-10 flex justify-center gap-3">
          <Link to={c.next}><Button variant="primary" size="lg" rightIcon="arrowRight">Get started — it's free</Button></Link>
        </div>
        <p className="text-xs text-neutral-500 mt-4">Takes about 5 minutes. You can save and come back later.</p>
      </main>
    </div>
  );
}

/* ============ HUB ONBOARDING — PROFILE ============ */
function HubOnboardingProfilePage() {
  return (
    <OnboardingShell
      steps={['Profile', 'Details', 'Verification', 'Listings', 'Plan']}
      current={0}
      title="Tell us about your hub"
      back="/app/onboarding/hub/welcome" next="/app/onboarding/hub/details"
      side={<TipsCard items={[
        'Clear hub names get 2× more clicks.',
        'Add a logo before publishing — it builds trust.',
        'Tags help us match you to relevant programs.',
      ]} />}>
      <div className="space-y-6">
        <Card>
          <div className="flex items-start gap-5">
            <div className="w-24 h-24 rounded-xl bg-neutral-100 flex items-center justify-center text-neutral-400">
              <Icon name="upload" size={24} />
            </div>
            <div className="flex-1">
              <h3 className="font-semibold mb-1">Hub logo</h3>
              <p className="text-sm text-neutral-500 mb-3">Square JPG or PNG, at least 400×400.</p>
              <Button variant="secondary" size="sm" leftIcon="upload">Upload logo</Button>
            </div>
          </div>
        </Card>
        <Card>
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Hub name" value="" placeholder="e.g. Kraf KL Studio" />
            <div>
              <label className="text-xs font-medium text-neutral-700 mb-1.5 block">Hub type</label>
              <select className="w-full h-10 px-3 text-sm border border-neutral-300 rounded-lg bg-white focus:outline-none focus:border-neutral-500">
                <option>Heritage Crafts</option>
                <option>Culinary</option>
                <option>Design & Tech</option>
                <option>Wellness</option>
                <option>Education</option>
              </select>
            </div>
            <div className="sm:col-span-2">
              <Field label="Tagline" value="" placeholder="One-liner that captures what you do" />
            </div>
            <div className="sm:col-span-2">
              <Field label="About" textarea value="" placeholder="What does your hub stand for? What's its story?" />
            </div>
          </div>
        </Card>
        <Card>
          <h3 className="font-semibold mb-3">Tags</h3>
          <div className="flex flex-wrap gap-2">
            {['Batik', 'Pottery', 'Cooking', 'Coffee', 'Workshops', 'Studio rentals', 'Photography', 'Programs', 'Heritage', 'Sustainability'].map(t => (
              <Chip key={t} active={['Batik', 'Workshops', 'Heritage'].includes(t)}>{t}</Chip>
            ))}
          </div>
        </Card>
      </div>
    </OnboardingShell>
  );
}

/* ============ EXPERIENCE ONBOARDING — SELECT TYPE ============ */
function ExperienceOnboardingTypePage() {
  const opts = [
    { t: 'Workshop', d: 'Hands-on session with a small group at your space.', icon: 'spark' },
    { t: 'Class series', d: 'Multi-session class running over weeks or months.', icon: 'graduation' },
    { t: 'Tour or visit', d: 'Guided walk, studio tour or location-based experience.', icon: 'map' },
    { t: 'Online masterclass', d: 'Pre-recorded video lessons + live Q&A.', icon: 'play' },
  ];
  const [pick, setPick] = useState('Workshop');
  return (
    <OnboardingShell
      steps={['Type', 'Basics', 'Tickets', 'Location', 'Photos', 'Publish']}
      current={0}
      title="What kind of experience is it?"
      back="/app/hub/services/experiences" next="/app/onboarding/experience/basics"
      side={<TipsCard items={[
        'Workshops with under 8 people earn 4.7+ stars on average.',
        'Add 1 hero shot + 4 supporting photos.',
        'Most-booked listings have crystal-clear titles.',
      ]} />}>
      <div className="grid sm:grid-cols-2 gap-4">
        {opts.map(o => (
          <button key={o.t} onClick={() => setPick(o.t)}
            className={`text-left p-5 rounded-xl border-2 transition-all bg-white ${pick === o.t ? 'border-primary shadow-md' : 'border-neutral-200 hover:border-neutral-400'}`}>
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center mb-3 ${pick === o.t ? 'bg-primary text-white' : 'bg-neutral-100 text-neutral-700'}`}>
              <Icon name={o.icon} size={18} />
            </div>
            <h3 className="font-semibold mb-1">{o.t}</h3>
            <p className="text-sm text-neutral-600">{o.d}</p>
            {pick === o.t && <div className="mt-3 flex items-center gap-1 text-xs text-primary font-medium"><Icon name="check" size={12} /> Selected</div>}
          </button>
        ))}
      </div>
    </OnboardingShell>
  );
}

/* ============ EXPERIENCE ONBOARDING — BASICS ============ */
function ExperienceOnboardingBasicsPage() {
  return (
    <OnboardingShell
      steps={['Type', 'Basics', 'Tickets', 'Location', 'Photos', 'Publish']}
      current={1}
      title="The basics"
      back="/app/onboarding/experience/select-type" next="/app/onboarding/experience/tickets"
      side={<TipsCard items={[
        'Titles with specific outcomes book 30% better.',
        'Keep the description to 3 short paragraphs.',
        'Mention what guests take home.',
      ]} />}>
      <Card>
        <div className="space-y-4">
          <Field label="Experience title" value="" placeholder="e.g. Traditional Batik Painting Workshop" />
          <Field label="Short summary" value="" placeholder="One sentence guests will see on cards" />
          <Field label="Full description" textarea value="" placeholder="What will guests do, learn and take home?" />
          <div className="grid sm:grid-cols-3 gap-3">
            <Field label="Duration (hours)" value="3" />
            <Field label="Group size" value="8" />
            <Field label="Min. age" value="12" />
          </div>
          <div>
            <label className="text-xs font-medium text-neutral-700 mb-1.5 block">Skill level</label>
            <div className="flex gap-2">
              {['Beginner', 'Intermediate', 'Advanced', 'All levels'].map(s => <Chip key={s} active={s === 'Beginner'}>{s}</Chip>)}
            </div>
          </div>
        </div>
      </Card>
    </OnboardingShell>
  );
}

/* ============ EXPERTISE ONBOARDING — BRIEF ============ */
function ExpertiseOnboardingBriefPage() {
  return (
    <OnboardingShell
      steps={['Brief', 'Scope', 'Pricing', 'Process', 'Publish']}
      current={0}
      title="Describe your service"
      back="/app/onboarding/expertise/welcome" next="/app/onboarding/expertise/scope"
      side={<TipsCard items={[
        'Specific service titles convert 2× better.',
        'Lead with the outcome, not the deliverable.',
        'Pre-defined packages reduce time-to-book by 60%.',
      ]} />}>
      <Card>
        <div className="space-y-4">
          <Field label="Service title" value="" placeholder="e.g. Brand Identity Sprint — 2 weeks" />
          <div>
            <label className="text-xs font-medium text-neutral-700 mb-1.5 block">Category</label>
            <div className="flex flex-wrap gap-2">
              {['Branding', 'Design', 'Engineering', 'Marketing', 'Strategy', 'Content', 'Sustainability'].map(c => (
                <Chip key={c} active={c === 'Branding'}>{c}</Chip>
              ))}
            </div>
          </div>
          <Field label="Outcome — what changes for the client?" textarea value="" placeholder="A complete brand book they can hand to their team & partners." />
          <Field label="Long description" textarea value="" placeholder="Walk us through what you do, who it's for, and what's included." />
        </div>
      </Card>
    </OnboardingShell>
  );
}

/* ============ JOB ONBOARDING — DETAILS ============ */
function JobOnboardingDetailsPage() {
  return (
    <OnboardingShell
      steps={['Details', 'Budget', 'Skills', 'Review']}
      current={0}
      title="Post a job"
      back="/app/hub/jobs/posts" next="/app/onboarding/job/budget"
      side={<TipsCard items={[
        'Be specific about deliverables.',
        'Include 1–2 examples of work you admire.',
        'Detailed posts get 3× more quality applicants.',
      ]} />}>
      <Card>
        <div className="space-y-4">
          <Field label="Job title" value="" placeholder="e.g. Brand Identity for D2C Skincare Launch" />
          <div className="grid sm:grid-cols-2 gap-3">
            <div>
              <label className="text-xs font-medium text-neutral-700 mb-1.5 block">Contract type</label>
              <div className="flex gap-2">
                {['Fixed', 'Hourly', 'Retainer'].map(t => <Chip key={t} active={t === 'Fixed'}>{t}</Chip>)}
              </div>
            </div>
            <Field label="Estimated duration" value="" placeholder="e.g. 4–6 weeks" />
          </div>
          <Field label="Project description" textarea value="" placeholder="What's the goal, scope and timeline?" />
        </div>
      </Card>
    </OnboardingShell>
  );
}

/* ============ LEARNER ONBOARDING — INTERESTS ============ */
function LearnerOnboardingInterestsPage() {
  const cats = [
    { t: 'Creative & Crafts', items: ['Batik & textiles', 'Pottery', 'Calligraphy', 'Illustration'] },
    { t: 'Wellbeing', items: ['Yoga', 'Meditation', 'Breathwork', 'Journaling'] },
    { t: 'Food & Drink', items: ['Baking', 'Coffee', 'Fermentation', 'Plant-based'] },
    { t: 'Business & Tech', items: ['AI tools', 'Branding', 'Sales', 'Product'] },
  ];
  const selected = ['Branding', 'AI tools', 'Baking'];
  return (
    <OnboardingShell
      steps={['Interests', 'Profile', 'Notifications', 'Done']}
      current={0}
      title="What are you interested in?"
      back="/app/onboarding/learner/welcome" next="/app/onboarding/learner/profile"
      side={<TipsCard items={[
        'Pick at least 3 to get useful recommendations.',
        "You can always change this later.",
      ]} />}>
      <Card>
        <div className="space-y-6">
          {cats.map(c => (
            <div key={c.t}>
              <h3 className="text-sm font-semibold mb-3">{c.t}</h3>
              <div className="flex flex-wrap gap-2">
                {c.items.map(it => <Chip key={it} active={selected.includes(it)}>{it}</Chip>)}
              </div>
            </div>
          ))}
        </div>
      </Card>
    </OnboardingShell>
  );
}

/* ============ EXPERT ONBOARDING — PROFILE ============ */
function ExpertOnboardingProfilePage() {
  return (
    <OnboardingShell
      steps={['Profile', 'Skills', 'Portfolio', 'Rates', 'Verify']}
      current={0}
      title="Build your expert profile"
      back="/app/onboarding/expert/welcome" next="/app/onboarding/expert/skills"
      side={<TipsCard items={[
        'Profiles with a real photo book 5× more sessions.',
        'A 60-second intro video helps you stand out.',
        'Mention exact tools and methodologies you use.',
      ]} />}>
      <div className="space-y-6">
        <Card>
          <div className="flex items-start gap-5">
            <Avatar name="?" size={96} />
            <div className="flex-1">
              <h3 className="font-semibold mb-1">Photo</h3>
              <p className="text-sm text-neutral-500 mb-3">A real, clear headshot. No logos, no group shots.</p>
              <Button variant="secondary" size="sm" leftIcon="upload">Upload photo</Button>
            </div>
          </div>
        </Card>
        <Card>
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="Full name" value="Faiz Fadhillah" />
            <Field label="Headline" value="" placeholder="e.g. Senior Brand Strategist · Studio Kuala" />
            <Field label="Based in" value="Kuala Lumpur, Malaysia" />
            <Field label="Years of experience" value="" placeholder="10+" />
            <div className="sm:col-span-2">
              <Field label="About you" textarea value="" placeholder="Tell clients who you are, what you ship, and who you love working with." />
            </div>
          </div>
        </Card>
      </div>
    </OnboardingShell>
  );
}

Object.assign(window, {
  OnboardingShell, OnboardingWelcomePage,
  HubOnboardingProfilePage,
  ExperienceOnboardingTypePage, ExperienceOnboardingBasicsPage,
  ExpertiseOnboardingBriefPage,
  JobOnboardingDetailsPage,
  LearnerOnboardingInterestsPage,
  ExpertOnboardingProfilePage,
});
