/* Mereka v2 — Add Service / "Post a listing" wizard
   Figma 5208-29918 (Basic Info), 5208-31735 & 5208-30335 (Listing Details),
   5208-33155 (Add field modal). Step 1 adds an Experience/Expertise choice. */

const SERVICE_STEPS = [
  { key: 'type', label: 'Select type', to: '/app/service/create/type' },
  { key: 'basics', label: 'Basic Info', to: '/app/service/create/basics' },
  { key: 'details', label: 'Listing Details', to: '/app/service/create/details' },
  { key: 'publish', label: 'Publish', to: '/app/service/create/publish' },
];

/* Remember the chosen listing kind across steps (prototype persistence) */
function getListingKind() { try { return localStorage.getItem('mereka_listing_kind') || 'Experience'; } catch (e) { return 'Experience'; } }
function setListingKind(k) { try { localStorage.setItem('mereka_listing_kind', k); } catch (e) {} }

function ServiceCreateShell({ active, children, footer }) {
  return (
    <div className="min-h-screen bg-neutral-50">
      <HomeHeader />
      <main className="max-w-[min(2560px,95vw)] mx-auto px-6 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-[200px_1fr] gap-8">
          <aside>
            <Link to="/app/hub/services/experiences" className="inline-flex items-center justify-center w-8 h-8 rounded-full hover:bg-neutral-100 text-neutral-600 mb-4" aria-label="Back">
              <Icon name="chevronLeft" size={18} />
            </Link>
            <h2 className="text-xl font-bold mb-6">Post a listing</h2>
            <nav className="space-y-1">
              {SERVICE_STEPS.map(s => {
                const isActive = active === s.key;
                return (
                  <Link key={s.key} to={s.to}
                    className={`block w-fit px-4 py-2 rounded-full text-sm transition-colors ${isActive ? 'bg-neutral-900 text-white font-semibold' : 'text-neutral-700 hover:bg-neutral-100'}`}>
                    {s.label}
                  </Link>
                );
              })}
            </nav>
          </aside>
          <div>
            {children}
            {footer && <div className="mt-3 bg-white border border-neutral-200 rounded-2xl px-6 py-4">{footer}</div>}
          </div>
        </div>
      </main>
    </div>
  );
}

/* Fake rich-text toolbar (visual only, matches Figma) */
function RichTextArea({ placeholder, value }) {
  return (
    <div className="border border-neutral-300 rounded-lg overflow-hidden focus-within:border-neutral-500">
      <textarea rows={4} placeholder={placeholder} defaultValue={value}
        className="w-full px-4 py-3 text-sm focus:outline-none resize-none" />
      <div className="flex items-center gap-1 px-3 py-2 border-t border-neutral-200 text-neutral-500">
        {['bold', 'italic', 'underline', 'link', 'listOrdered', 'list'].map((k, i) => (
          <button key={i} className="w-8 h-8 rounded hover:bg-neutral-100 flex items-center justify-center text-[13px] font-bold">
            {k === 'bold' ? 'B' : k === 'italic' ? <span className="italic font-serif">I</span> : k === 'underline' ? <span className="underline">U</span>
              : k === 'link' ? <Icon name="external" size={14} /> : <Icon name="menu" size={14} />}
          </button>
        ))}
      </div>
    </div>
  );
}

function TagsField() {
  return (
    <div className="flex items-center gap-2">
      <div className="inline-flex items-center h-9 px-4 rounded-full border border-neutral-300 text-sm text-neutral-500">Type Tags</div>
      <button className="w-9 h-9 rounded-full border border-neutral-300 flex items-center justify-center text-neutral-500 hover:bg-neutral-50"><Icon name="plus" size={15} /></button>
    </div>
  );
}

/* ============ STEP 0 — Select type (Experience vs Expertise) ============ */
function ServiceCreateTypePage() {
  const [kind, setKind] = useState(getListingKind());
  const choose = (k) => { setKind(k); setListingKind(k); };
  const opts = [
    { k: 'Experience', icon: 'calendar', desc: 'A workshop, class, event or tour people can book and attend.',
      points: ['Category, mode & location', 'Booking details & tickets', 'Gallery & schedule'] },
    { k: 'Expertise', icon: 'userStar', desc: 'A consultation, coaching or project delivered by you as an expert.',
      points: ['Category & delivery mode', 'Scope, timeline & budget', 'Requirements & outcomes'] },
  ];
  return (
    <ServiceCreateShell active="type" footer={<ContinueFooter next="/app/service/create/basics" />}>
      <div className="bg-white border border-neutral-200 rounded-2xl p-8">
        <h1 className="text-xl font-bold tracking-tight">What would you like to list?</h1>
        <p className="text-sm text-neutral-500 mt-1.5">Experiences and Expertise collect different details, so pick the one that fits — this shapes the fields you'll fill in on the next steps.</p>
        <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-4">
          {opts.map(o => {
            const on = kind === o.k;
            return (
              <button key={o.k} onClick={() => choose(o.k)}
                className={`text-left rounded-2xl border-2 p-6 transition-colors ${on ? 'border-neutral-900 bg-neutral-50' : 'border-neutral-200 hover:border-neutral-300'}`}>
                <div className="flex items-center justify-between">
                  <span className="w-11 h-11 rounded-xl bg-neutral-900 text-white flex items-center justify-center"><Icon name={o.icon} size={20} /></span>
                  <span className={`w-6 h-6 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${on ? 'border-neutral-900' : 'border-neutral-300'}`}>
                    {on && <span className="w-3 h-3 rounded-full bg-neutral-900" />}
                  </span>
                </div>
                <h3 className="font-bold text-lg mt-4">{o.k}</h3>
                <p className="text-sm text-neutral-500 mt-1.5 leading-snug">{o.desc}</p>
                <ul className="mt-4 space-y-1.5">
                  {o.points.map(p => (
                    <li key={p} className="flex items-center gap-2 text-sm text-neutral-700"><Icon name="check" size={14} className="text-green-600" /> {p}</li>
                  ))}
                </ul>
              </button>
            );
          })}
        </div>
      </div>
    </ServiceCreateShell>
  );
}

/* ============ STEP 1 — Basic Info (Figma 5208-29918) ============ */
const VALUE_TYPES = [
  'I can provide a service',
  'I can teach or guide people',
  'I have one-off tasks people can help with',
  'I can host an activity or event',
];

function ServiceCreateBasicsPage() {
  const params = new URLSearchParams(typeof location !== 'undefined' ? location.search : '');
  const editId = params.get('edit');
  const editName = params.get('name') || '';
  const editDesc = params.get('desc') || '';
  const editing = !!(editId || editName);
  const kind = params.get('kind') || getListingKind();
  const [value, setValue] = useState('I can host an activity or event');
  return (
    <ServiceCreateShell active="basics" footer={<ContinueFooter next="/app/service/create/details" />}>
      <div className="bg-white border border-neutral-200 rounded-2xl p-8">
        {editing && (
          <div className="flex items-center gap-2 mb-5 -mt-1 text-[13px]">
            <span className="inline-flex items-center gap-1.5 px-2.5 h-6 rounded-full bg-amber-50 text-amber-700 font-semibold"><Icon name="edit" size={12} /> Editing</span>
            <span className="font-semibold text-neutral-900">{editName}</span>
          </div>
        )}
        {/* Selected listing type summary (chosen in the previous step) */}
        <div className="flex items-center gap-3 mb-7 pb-6 border-b border-neutral-100">
          <span className="text-xs font-semibold text-neutral-400 uppercase tracking-wide">Listing type</span>
          <span className="inline-flex items-center gap-1.5 px-3 h-7 rounded-full bg-neutral-900 text-white text-[13px] font-semibold">
            <Icon name={kind === 'Expertise' ? 'userStar' : 'calendar'} size={13} /> {kind}
          </span>
          <Link to="/app/service/create/type" className="text-sm font-semibold text-blue-600 hover:underline">Change</Link>
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-[1fr_300px] gap-0">
          <div className="space-y-8 lg:border-r lg:border-neutral-200 lg:pr-10">
            {/* Listing Title */}
            <div>
              <FieldLabel>Listing Title</FieldLabel>
              <FieldHelp className="mt-1">Short, clear name of what you're offering<br />Example: "Beginner Crochet Workshop" / "Video Editing Services"</FieldHelp>
              <div className="mt-4"><PgmInput key={editId || 'new'} value={editName} placeholder="Title" /></div>
              <p className="text-xs text-neutral-400 mt-1.5">0/70 max</p>
            </div>

            {/* Describe your offer */}
            <div>
              <FieldLabel>Describe your offer</FieldLabel>
              <FieldHelp className="mt-1">One or two sentences describing the offer<br />Example: "Hands-on workshop teaching basic stitches"</FieldHelp>
              <div className="mt-4"><RichTextArea key={editId || 'new-d'} value={editDesc} placeholder="Description" /></div>
            </div>

            {/* What type of value */}
            <div>
              <FieldLabel>What type of value are you offering?</FieldLabel>
              <div className="mt-3 space-y-1">
                {VALUE_TYPES.map(v => (
                  <button key={v} onClick={() => setValue(v)} className="flex items-center gap-3 py-1.5 w-full text-left">
                    <span className={`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${value === v ? 'border-neutral-900' : 'border-neutral-400'}`}>
                      {value === v && <span className="w-2.5 h-2.5 rounded-full bg-neutral-900" />}
                    </span>
                    <span className="text-sm text-neutral-800">{v}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* Keyword tags */}
            <div>
              <FieldLabel optional>Keyword tags</FieldLabel>
              <FieldHelp className="mt-1">Tag your service with relevant keywords to the services you offer. Maximum 5 tags.</FieldHelp>
              <div className="mt-4"><TagsField /></div>
            </div>
          </div>

          <div className="lg:pt-1 lg:pl-10">
            <TipsBlock
              body={
                <p className="text-sm text-neutral-700 leading-relaxed">
                  Make your title descriptive and exciting! Use key words that your clients would likely use to search for services like yours.
                  <span className="block mt-4">E.g. LinkedIn Zero to Hero: LinkedIn Profile Review &amp; Optimisation</span>
                </p>
              }
            />
          </div>
        </div>
      </div>
    </ServiceCreateShell>
  );
}

/* ============ STEP 2 — Listing Details (Figma 5208-31735 / 30335) ============ */
const EXPERIENCE_CATEGORIES = [
  { name: 'Event', desc: 'A one-off themed occasion, eg. film screening or comedy night' },
  { name: 'Talk', desc: "An Experience offering an Expert's insight into a particular subject." },
  { name: 'Program', desc: 'A comprehensive Experience involving various activities like workshops, mentorship, pitches.' },
  { name: 'Workshop', desc: 'A hands-on themed Experience often involving group interaction.' },
  { name: 'Show & Exhibition', desc: 'This may involve a range of events, eg. performances or art exhibitions.' },
];
const EXPERTISE_CATEGORIES = [
  { name: 'Consultation', desc: "One-on-one expert advice sessions tailored to a client's needs." },
  { name: 'Coaching', desc: 'Ongoing guidance to help clients build a skill or reach a goal.' },
  { name: 'Audit & Review', desc: 'A structured assessment with actionable recommendations.' },
  { name: 'Project', desc: 'A scoped deliverable completed for the client end-to-end.' },
  { name: 'Retainer', desc: 'Ongoing expertise delivered on a recurring monthly basis.' },
];

/* All fields that can appear in the details form. `base` = always present. */
const DETAIL_FIELDS = [
  { key: 'category', base: true, added: true },
  { key: 'mode', base: true, added: true },
  { key: 'audience', label: 'Target Audience', added: true, desc: 'Describe who this listing is best suited for.' },
  { key: 'booking', label: 'Booking details', added: true, desc: 'Set how and when people can book this listing.' },
  { key: 'tickets', label: 'Tickets', added: true, desc: 'Create ticket types, pricing and capacity.' },
  { key: 'yourpage', label: 'Your Page', added: false, desc: 'A hands-on themed Experience often involving group interaction.' },
  { key: 'outcomes', label: 'Learning outcomes', added: false, desc: 'A hands-on themed Experience often involving group interaction.' },
  { key: 'instructions', label: 'Instructions', added: false, desc: 'A hands-on themed Experience often involving group interaction.' },
  { key: 'timeline', label: 'Timeline & budget', added: false, desc: 'This may involve a range of events, eg. performances or art exhibitions.' },
  { key: 'requirements', label: 'Requirements', added: false, desc: 'A hands-on themed Experience often involving group interaction.' },
];

function Accordion({ title, defaultOpen = false, children }) {
  const [open, setOpen] = useState(defaultOpen);
  return (
    <div className="bg-white border border-neutral-200 rounded-2xl overflow-hidden">
      <button onClick={() => setOpen(o => !o)} className="w-full flex items-center justify-between gap-3 px-6 py-5 text-left">
        <span className="text-base font-bold text-neutral-900">{title}</span>
        <Icon name={open ? 'chevronUp' : 'chevronDown'} size={18} className="text-neutral-400" />
      </button>
      {open && <div className="px-6 pb-6 -mt-1">{children}</div>}
    </div>
  );
}

function AddrField({ label, placeholder }) {
  return (
    <div>
      <label className="block text-xs text-neutral-500 mb-1.5">{label}</label>
      <input placeholder={placeholder} className="w-full h-11 px-4 text-sm border border-neutral-300 rounded-lg bg-white focus:outline-none focus:border-neutral-500" />
    </div>
  );
}

function CategorySection({ kind }) {
  const cats = kind === 'Expertise' ? EXPERTISE_CATEGORIES : EXPERIENCE_CATEGORIES;
  const [sel, setSel] = useState(null);
  const lower = kind.toLowerCase();
  return (
    <div>
      <h3 className="text-xl font-bold">What type of {lower} will you offer?</h3>
      <FieldHelp className="mt-1.5">{kind}s may consist of multiple slots and/or run on a recurring basis - these can be added later.</FieldHelp>
      <div className="mt-5 grid grid-cols-1 md:grid-cols-3 gap-3">
        {cats.map(c => {
          const on = sel === c.name;
          return (
            <button key={c.name} onClick={() => setSel(c.name)}
              className={`text-left rounded-xl border p-4 transition-colors ${on ? 'border-neutral-900 ring-1 ring-neutral-900' : 'border-neutral-200 hover:border-neutral-300'}`}>
              <p className="font-bold text-sm">{c.name}</p>
              <p className="text-xs text-neutral-500 mt-1.5 leading-snug">{c.desc}</p>
            </button>
          );
        })}
      </div>
      <h3 className="text-xl font-bold mt-8">Select up to 3 themes for your {kind}</h3>
      <FieldHelp className="mt-1.5">This will help users to search for and book your {kind}.</FieldHelp>
      <div className="mt-4">
        <button className="w-full sm:w-[320px] flex items-center justify-between gap-3 rounded-xl border border-neutral-200 px-4 py-3.5 hover:border-neutral-300">
          <span className="text-sm font-semibold text-neutral-800">Add theme</span>
          <span className="w-8 h-8 rounded-full border border-neutral-300 flex items-center justify-center text-neutral-400"><Icon name="plus" size={15} /></span>
        </button>
      </div>
    </div>
  );
}

function ModeSection({ kind }) {
  const [mode, setMode] = useState('Physical');
  const lower = kind.toLowerCase();
  return (
    <div className="grid grid-cols-1 lg:grid-cols-[1fr_280px] gap-0">
      <div className="lg:border-r lg:border-neutral-200 lg:pr-10">
        <h3 className="text-xl font-bold">Are you hosting your {kind} physically or online?</h3>
        <FieldHelp className="mt-1.5">Online {kind}s can be hosted from anywhere via video conferencing software such as Zoom or Google Meet, whereas physical {kind}s must be conducted in either your own space or any venue you are approved to use.</FieldHelp>
        <div className="mt-4 space-y-1">
          {['Physical', 'Online'].map(m => (
            <button key={m} onClick={() => setMode(m)} className="flex items-center gap-3 py-1.5 w-full text-left">
              <span className={`w-5 h-5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${mode === m ? 'border-neutral-900' : 'border-neutral-400'}`}>
                {mode === m && <span className="w-2.5 h-2.5 rounded-full bg-neutral-900" />}
              </span>
              <span className="text-sm text-neutral-800">{m}</span>
            </button>
          ))}
        </div>
        <h3 className="text-xl font-bold mt-7">Share the location of your {kind}!</h3>
        <div className="mt-4 space-y-4">
          <AddrField label="Street Address" placeholder="" />
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <AddrField label="Country" placeholder="" />
            <AddrField label="State (if any)" placeholder="" />
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <AddrField label="Town/City" placeholder="" />
            <AddrField label="Postcode" placeholder="" />
          </div>
        </div>
      </div>
      <div className="lg:pt-1 lg:pl-10">
        <TipsBlock placeholder={false} body={
          <p className="text-sm text-neutral-700 leading-relaxed">If your {kind} is hybrid, you will need to list 2 separate {lower}s: one listing for physical bookings and another listing for virtual bookings.</p>
        } />
        <PinItTips />
      </div>
    </div>
  );
}

function PlaceholderSection({ label }) {
  return (
    <div className="space-y-4">
      <FieldHelp>Configure the {label.toLowerCase()} for this listing.</FieldHelp>
      <PgmInput placeholder={`${label}…`} />
      <PgmTextarea placeholder={`Add ${label.toLowerCase()} details`} />
    </div>
  );
}

function AddFieldModal({ fields, active, onToggle, onClose, kind = 'Experience' }) {
  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center p-6 overflow-y-auto" style={{ background: 'rgba(0,0,0,0.4)' }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} className="bg-white rounded-2xl w-full max-w-[min(2000px,92vw)] my-8 p-7" style={{ boxShadow: '0 24px 64px rgba(0,0,0,0.25)' }}>
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-3xl font-bold">Add field</h2>
          <button onClick={onClose} className="w-9 h-9 rounded-full flex items-center justify-center hover:bg-neutral-100 text-neutral-500"><Icon name="close" size={20} /></button>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {fields.map(f => {
            const isActive = active.includes(f.key);
            const locked = f.base;
            return (
              <div key={f.key} className="rounded-xl border border-neutral-200 p-4">
                <div className="flex items-start justify-between gap-2">
                  <div className="flex items-center gap-2">
                    <span className="font-bold text-[15px]">{f.label || (f.key === 'category' ? `${kind} category` : `${kind} mode`)}</span>
                    {isActive && <span className="text-[11px] font-bold bg-neutral-200 text-neutral-600 px-2 py-0.5 rounded uppercase tracking-wide">Added</span>}
                  </div>
                  {isActive
                    ? <button disabled={locked} onClick={() => !locked && onToggle(f.key)} className={`text-neutral-400 ${locked ? 'opacity-40 cursor-not-allowed' : 'hover:text-red-500'}`}><Icon name="trash" size={16} /></button>
                    : <button onClick={() => onToggle(f.key)} className="w-6 h-6 rounded-full border border-neutral-300 flex items-center justify-center text-neutral-400 hover:border-neutral-500 hover:text-neutral-700"><Icon name="plus" size={13} /></button>}
                </div>
                <p className="text-xs text-neutral-500 mt-2 leading-snug">{f.desc || `${kindLabel(f.key)}`}</p>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
function kindLabel() { return 'Experiences may consist of multiple slots and/or run on a recurring basis - these can be added later.'; }

function ServiceCreateDetailsPage() {
  const kind = getListingKind();
  const [active, setActive] = useState(DETAIL_FIELDS.filter(f => f.added).map(f => f.key));
  const [modal, setModal] = useState(false);
  const toggle = (k) => setActive(a => a.includes(k) ? a.filter(x => x !== k) : [...a, k]);
  const fieldsFor = (key) => {
    if (key === 'category') return { title: `${kind} category`, node: <CategorySection kind={kind} />, open: true };
    if (key === 'mode') return { title: `${kind} mode`, node: <ModeSection kind={kind} /> };
    const f = DETAIL_FIELDS.find(x => x.key === key);
    return { title: f.label, node: <PlaceholderSection label={f.label} /> };
  };
  const ordered = DETAIL_FIELDS.filter(f => active.includes(f.key)).map(f => f.key);

  return (
    <ServiceCreateShell active="details" footer={
      <div className="flex items-center justify-end gap-3">
        <button onClick={() => setModal(true)} className="inline-flex items-center gap-2 h-11 px-5 rounded-full border border-neutral-300 text-sm font-semibold hover:bg-neutral-50">
          Add Field <span className="w-6 h-6 rounded-full border border-neutral-300 flex items-center justify-center"><Icon name="plus" size={13} /></span>
        </button>
        <Link to="/app/service/create/publish"><button className="inline-flex items-center px-6 h-11 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">Save &amp; Continue</button></Link>
      </div>
    }>
      <div className="space-y-4">
        {ordered.map((key, i) => {
          const cfg = fieldsFor(key);
          return <Accordion key={key} title={cfg.title} defaultOpen={i === 0}>{cfg.node}</Accordion>;
        })}
        <Accordion title="Gallery &amp; info"><PlaceholderSection label="Gallery & info" /></Accordion>
      </div>
      {modal && <AddFieldModal fields={DETAIL_FIELDS} active={active} onToggle={toggle} onClose={() => setModal(false)} kind={kind} />}
    </ServiceCreateShell>
  );
}

/* ============ STEP 3 — Publish ============ */
function ServiceCreatePublishPage() {
  const kind = getListingKind();
  return (
    <ServiceCreateShell active="publish" footer={
      <div className="flex items-center justify-end gap-3">
        <Link to="/app/hub/services/experiences"><button className="inline-flex items-center px-6 h-11 rounded-full bg-neutral-900 text-white text-sm font-semibold hover:bg-neutral-800">Publish listing</button></Link>
      </div>
    }>
      <div className="bg-white border border-neutral-200 rounded-2xl p-8">
        <h1 className="text-xl font-bold">Review &amp; publish</h1>
        <p className="text-sm text-neutral-500 mt-1.5">Give your listing a final check before it goes live.</p>
        <div className="mt-6 space-y-3">
          <div className="flex items-center justify-between rounded-xl border border-neutral-200 px-5 py-4">
            <div>
              <p className="text-xs text-neutral-500 uppercase tracking-wide">Listing type</p>
              <p className="font-bold mt-0.5">{kind}</p>
            </div>
            <Link to="/app/service/create/type" className="text-sm font-semibold text-blue-600 hover:underline">Edit</Link>
          </div>
          {['Basic info', 'Listing details', 'Gallery & info'].map(s => (
            <div key={s} className="flex items-center justify-between rounded-xl border border-neutral-200 px-5 py-4">
              <div className="flex items-center gap-2.5">
                <span className="w-6 h-6 rounded-full bg-green-100 text-green-600 flex items-center justify-center"><Icon name="check" size={14} strokeWidth={3} /></span>
                <span className="font-semibold text-sm">{s}</span>
              </div>
              <span className="text-xs text-neutral-500">Complete</span>
            </div>
          ))}
        </div>
        <div className="mt-6 flex items-start gap-2.5 rounded-xl bg-blue-50 border border-blue-100 px-5 py-4">
          <Icon name="spark" size={18} className="text-blue-500 mt-0.5" />
          <p className="text-sm text-blue-800">Your listing will be reviewed and set to <b>Live</b> once approved. You can keep editing it from Manage Services.</p>
        </div>
      </div>
    </ServiceCreateShell>
  );
}

Object.assign(window, {
  ServiceCreateTypePage, ServiceCreateBasicsPage, ServiceCreateDetailsPage, ServiceCreatePublishPage,
  getListingKind, setListingKind,
});
