/* GoWithMe — contribution composers (3 switchable variants).
   variant: 'quick'  → single bottom sheet (fast)
            'guided' → full-screen 3-step wizard (thorough)
            'ai'     → GoWithMe AI interviews you (conversational)
   All build a contribution item and call onSubmit(item). */

const POINTS = { review: 50, story: 120, tip: 40, photo: 30, correction: 60 };
const CORRECTION_FIELDS = ['Opening hours', 'Entry fee', 'Description', 'Best time to visit', 'Facilities', 'Other'];
const PLACEHOLDER = {
  review: 'What was your visit like? What would you tell another traveler?',
  story: "Share what you know — the history, a legend, a detail most visitors miss…",
  tip: 'Your practical advice — fees, timing, transport, scams to avoid…',
  photo: 'Add a caption (optional)…',
  correction: "What's inaccurate, and what should it say instead?",
};

let subSeq = 500;
const meAuthor = () => ({
  name: HM.ME.name, initials: HM.ME.initials, photo: HM.ME.photo, role: 'traveler',
  flag: HM.ME.flag, badges: HM.ME.badges, sub: `Level ${HM.ME.level} · ${HM.ME.levelName}`,
});
function buildItem(type, f) {
  const learns = { story: 'reviewing', tip: 'reviewing', correction: 'reviewing' };
  return {
    id: 'me' + (++subSeq), type, author: meAuthor(), date: 'Just now', helpful: 0, mine: true,
    rating: f.rating, sub: f.sub, title: f.title, text: f.text, tags: f.tags, field: f.field,
    photos: f.photos && f.photos.length ? f.photos : undefined, aiStatus: learns[type],
  };
}
function validate(type, d) {
  if (type === 'review') return d.rating > 0 && d.text.trim().length > 3;
  if (type === 'story') return d.title.trim().length > 2 && d.text.trim().length > 10;
  if (type === 'tip') return d.text.trim().length > 5 && d.tags.length > 0;
  if (type === 'photo') return d.photos.length > 0;
  if (type === 'correction') return !!d.field && d.text.trim().length > 5;
  return false;
}
const emptyDraft = (type) => ({ type, rating: 0, sub: { value: 0, crowds: 0, safety: 0 }, title: '', text: '', tags: [], field: '', photos: [] });

/* ── shared field atoms ── */
function CField({ value, onChange, placeholder, rows = 4, autoFocus }) {
  return (
    <textarea value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} rows={rows} autoFocus={autoFocus}
      style={{ width: '100%', border: `1px solid ${T.line}`, borderRadius: 14, background: T.white, padding: '13px 15px',
        fontFamily: SANS, fontSize: 15, lineHeight: 1.5, color: T.ink, resize: 'none', outline: 'none', boxSizing: 'border-box' }} />
  );
}
function LineInput({ value, onChange, placeholder, autoFocus }) {
  return (
    <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} autoFocus={autoFocus}
      style={{ width: '100%', border: `1px solid ${T.line}`, borderRadius: 14, background: T.white, padding: '13px 15px',
        fontFamily: SANS, fontSize: 16, fontWeight: 600, color: T.ink, outline: 'none', boxSizing: 'border-box' }} />
  );
}
function FieldLabel({ children, hint }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, margin: '0 0 9px' }}>
      <span style={{ fontFamily: SANS, fontWeight: 800, fontSize: 14, color: T.ink }}>{children}</span>
      {hint && <span style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted }}>{hint}</span>}
    </div>
  );
}

/* photo adder — taps append placeholder shots from the place's own imagery */
function PhotoAdder({ photos, set, place }) {
  const pool = [{ img: place.gallery && place.gallery[0] }, { grad: place.grad }, { img: place.img }, { grad: HM.GRAD.sunset }, { grad: HM.GRAD.jungle }];
  const add = () => set([...photos, pool[photos.length % pool.length]]);
  const remove = (i) => set(photos.filter((_, j) => j !== i));
  return (
    <div style={{ display: 'flex', gap: 9, flexWrap: 'wrap' }}>
      {photos.map((p, i) => (
        <div key={i} style={{ position: 'relative' }}>
          <Photo p={p} size={78} radius={12} />
          <button onClick={() => remove(i)} style={{ position: 'absolute', top: -6, right: -6, width: 22, height: 22, borderRadius: 999, background: T.ink, border: '2px solid #fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="x" size={12} color="#fff" />
          </button>
        </div>
      ))}
      {photos.length < 5 && (
        <button onClick={add} style={{ width: 78, height: 78, borderRadius: 12, border: `1.5px dashed ${T.muted}`, background: T.cream2, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
          <Icon name="camera" size={20} color={T.body} />
          <span style={{ fontFamily: SANS, fontSize: 10.5, fontWeight: 700, color: T.body }}>Add</span>
        </button>
      )}
    </div>
  );
}

/* segmented sub-rating rows */
function SubRatingInputs({ sub, set }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
      {HM.SUBRATINGS.map((s) => (
        <div key={s.key} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span style={{ fontFamily: SANS, fontWeight: 600, fontSize: 14, color: T.body }}>{s.label}</span>
          <StarInput value={sub[s.key]} onChange={(v) => set({ ...sub, [s.key]: v })} size={22} gap={5} />
        </div>
      ))}
    </div>
  );
}

/* the type-specific form body, shared by quick + guided */
function DraftForm({ type, draft, set, place }) {
  const upd = (patch) => set({ ...draft, ...patch });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {type === 'review' && (
        <React.Fragment>
          <div>
            <FieldLabel>Your overall rating</FieldLabel>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <StarInput value={draft.rating} onChange={(v) => upd({ rating: v })} />
              {draft.rating > 0 && <span style={{ fontFamily: DISP, fontWeight: 800, fontSize: 22, color: T.ink }}>{draft.rating}.0</span>}
            </div>
          </div>
          <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 14, padding: 15 }}>
            <FieldLabel hint="optional">Rate the details</FieldLabel>
            <SubRatingInputs sub={draft.sub} set={(v) => upd({ sub: v })} />
          </div>
          <div><FieldLabel>Your review</FieldLabel><CField value={draft.text} onChange={(v) => upd({ text: v })} placeholder={PLACEHOLDER.review} rows={5} /></div>
        </React.Fragment>
      )}

      {type === 'story' && (
        <React.Fragment>
          <div><FieldLabel hint="give it a title">History &amp; story</FieldLabel><LineInput value={draft.title} onChange={(v) => upd({ title: v })} placeholder="e.g. The legend behind the west-facing gate" autoFocus /></div>
          <div><CField value={draft.text} onChange={(v) => upd({ text: v })} placeholder={PLACEHOLDER.story} rows={7} /></div>
          <div style={{ display: 'flex', gap: 9, alignItems: 'flex-start', background: T.tealBg, border: `1px solid ${T.teal}2e`, borderRadius: 12, padding: '11px 13px' }}>
            <Icon name="sparkle" size={16} color={T.teal} />
            <span style={{ fontFamily: SANS, fontSize: 12.5, lineHeight: 1.45, color: T.tealDk, fontWeight: 600 }}>Local knowledge and history are reviewed, then woven into this place's AI audio guide — with credit to you.</span>
          </div>
        </React.Fragment>
      )}

      {type === 'tip' && (
        <React.Fragment>
          <div>
            <FieldLabel>What's your tip about?</FieldLabel>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {HM.TIP_TAGS.map((t) => {
                const on = draft.tags.includes(t);
                return (
                  <button key={t} onClick={() => upd({ tags: on ? draft.tags.filter((x) => x !== t) : [...draft.tags, t] })} style={{
                    padding: '9px 14px', borderRadius: 999, cursor: 'pointer', fontFamily: SANS, fontWeight: 700, fontSize: 13,
                    border: on ? `1px solid ${T.teal}` : `1px solid ${T.line}`, background: on ? T.teal : T.white, color: on ? '#fff' : T.body, transition: 'all .15s',
                  }}>{t}</button>
                );
              })}
            </div>
          </div>
          <div><FieldLabel>Your tip</FieldLabel><CField value={draft.text} onChange={(v) => upd({ text: v })} placeholder={PLACEHOLDER.tip} rows={5} /></div>
        </React.Fragment>
      )}

      {type === 'photo' && (
        <React.Fragment>
          <div><FieldLabel hint="up to 5">Your photos</FieldLabel><PhotoAdder photos={draft.photos} set={(v) => upd({ photos: v })} place={place} /></div>
          <div><FieldLabel hint="optional">Caption</FieldLabel><CField value={draft.text} onChange={(v) => upd({ text: v })} placeholder={PLACEHOLDER.photo} rows={3} /></div>
        </React.Fragment>
      )}

      {type === 'correction' && (
        <React.Fragment>
          <div>
            <FieldLabel>What needs fixing?</FieldLabel>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {CORRECTION_FIELDS.map((f) => {
                const on = draft.field === f;
                return (
                  <button key={f} onClick={() => upd({ field: f })} style={{
                    padding: '9px 14px', borderRadius: 999, cursor: 'pointer', fontFamily: SANS, fontWeight: 700, fontSize: 13,
                    border: on ? `1px solid ${T.goldDk}` : `1px solid ${T.line}`, background: on ? T.goldBg : T.white, color: on ? T.goldDk : T.body, transition: 'all .15s',
                  }}>{f}</button>
                );
              })}
            </div>
          </div>
          <div><FieldLabel>Suggested correction</FieldLabel><CField value={draft.text} onChange={(v) => upd({ text: v })} placeholder={PLACEHOLDER.correction} rows={5} /></div>
        </React.Fragment>
      )}

      {/* optional photos for review / story / tip */}
      {(type === 'review' || type === 'story' || type === 'tip') && (
        <div><FieldLabel hint="optional">Add photos</FieldLabel><PhotoAdder photos={draft.photos} set={(v) => upd({ photos: v })} place={place} /></div>
      )}
    </div>
  );
}

/* type selector chips (quick composer) */
function TypeSelector({ value, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 8, overflowX: 'auto', margin: '0 -22px', padding: '2px 22px 2px' }}>
      {HM.CTYPE_ORDER.map((t) => {
        const c = HM.CTYPES[t]; const on = value === t;
        return (
          <button key={t} onClick={() => onChange(t)} style={{
            flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6, padding: '9px 14px', borderRadius: 999, cursor: 'pointer',
            border: on ? `1.5px solid ${c.color}` : `1px solid ${T.line}`, background: on ? c.bg : T.white,
            fontFamily: SANS, fontWeight: 700, fontSize: 13.5, color: on ? c.color : T.body, whiteSpace: 'nowrap', transition: 'all .15s',
          }}>
            <Icon name={c.icon} size={15} color={on ? c.color : T.muted} />{c.label}
          </button>
        );
      })}
    </div>
  );
}

/* ═══ Variant 1 — Quick bottom sheet ═══ */
function QuickComposer({ place, initialType, onClose, onSubmit }) {
  const [draft, setDraft] = React.useState(() => emptyDraft(initialType || 'review'));
  const type = draft.type;
  const ok = validate(type, draft);
  const setType = (t) => setDraft({ ...emptyDraft(t), text: draft.text, photos: draft.photos });

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 70, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={onClose} className="gw-back-in" style={{ position: 'absolute', inset: 0, background: 'rgba(8,18,32,0.5)' }} />
      <div className="gw-sheet-in" style={{ position: 'relative', background: T.cream, borderTopLeftRadius: 26, borderTopRightRadius: 26, maxHeight: '92%', display: 'flex', flexDirection: 'column', boxShadow: '0 -20px 50px rgba(0,0,0,0.35)' }}>
        <div style={{ padding: '12px 22px 10px', flexShrink: 0 }}>
          <div style={{ width: 42, height: 5, borderRadius: 999, background: T.line, margin: '0 auto 14px' }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ flex: 1 }}>
              <h2 style={{ fontFamily: DISP, fontWeight: 800, fontSize: 22, color: T.ink, margin: 0 }}>Share your experience</h2>
              <div style={{ fontFamily: SANS, fontSize: 13, color: T.muted, marginTop: 1 }}>{place.name}</div>
            </div>
            <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 11, background: T.white, border: `1px solid ${T.line}`, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="x" size={18} color={T.body} />
            </button>
          </div>
        </div>

        <div style={{ flexShrink: 0, padding: '4px 0 12px', borderBottom: `1px solid ${T.line}` }}>
          <TypeSelector value={type} onChange={setType} />
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '18px 22px 16px' }}>
          <DraftForm type={type} draft={draft} set={setDraft} place={place} />
        </div>

        <div style={{ flexShrink: 0, padding: '13px 22px 20px', borderTop: `1px solid ${T.line}`, background: T.cream, display: 'flex', alignItems: 'center', gap: 13 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: SANS, fontSize: 12.5, color: T.muted, fontWeight: 600 }}>
            <Icon name="award" size={16} color={T.gold} />+{POINTS[type]} pts
          </div>
          <button disabled={!ok} onClick={() => onSubmit(buildItem(type, draft))} className={ok ? 'gw-press' : ''} style={{
            flex: 1, padding: 16, borderRadius: 15, border: 'none', cursor: ok ? 'pointer' : 'default',
            background: ok ? T.navy : '#cfd8d4', color: '#fff', fontFamily: SANS, fontWeight: 800, fontSize: 16,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            Post {HM.CTYPES[type].label}<Icon name="send" size={17} color="#fff" />
          </button>
        </div>
      </div>
    </div>
  );
}

/* ═══ Variant 2 — Guided 3-step wizard ═══ */
function GuidedComposer({ place, initialType, onClose, onSubmit }) {
  const [step, setStep] = React.useState(initialType ? 2 : 1);
  const [draft, setDraft] = React.useState(() => emptyDraft(initialType || 'review'));
  const type = draft.type;
  const ok = validate(type, draft);

  const pick = (t) => { setDraft(emptyDraft(t)); setStep(2); };
  const preview = buildItem(type, draft);

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 70, background: T.cream, display: 'flex', flexDirection: 'column' }} className="gw-sheet-in">
      {/* header + progress */}
      <div style={{ background: T.navy, paddingBottom: 16, borderBottomLeftRadius: 22, borderBottomRightRadius: 22, flexShrink: 0 }}>
        <StatusBar light />
        <div style={{ padding: '2px 20px 0' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <button onClick={step > 1 && !initialType ? () => setStep(step - 1) : onClose} style={{ width: 40, height: 40, borderRadius: 11, background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name={step > 1 && !initialType ? 'arrow-left' : 'x'} size={19} color="#fff" />
            </button>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: SANS, fontSize: 12, color: 'rgba(255,255,255,0.55)', fontWeight: 600 }}>Contribute · {place.name}</div>
              <div style={{ fontFamily: DISP, fontWeight: 700, fontSize: 21, color: '#fff' }}>
                {step === 1 ? 'What to share' : step === 2 ? HM.CTYPES[type].verb : 'Review & post'}
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
            {[1, 2, 3].map((s) => (
              <div key={s} style={{ flex: 1, height: 5, borderRadius: 999, background: s <= step ? T.gold : 'rgba(255,255,255,0.16)', transition: 'background .3s' }} />
            ))}
          </div>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto' }}>
        <div style={{ padding: '20px 22px 130px' }}>
          {/* Step 1 — choose */}
          {step === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {HM.CTYPE_ORDER.map((t) => {
                const c = HM.CTYPES[t];
                const desc = { review: 'Rate it and tell others about your visit', story: 'Share history, legends or details you know', tip: 'Practical advice on fees, timing, transport', photo: 'Upload photos from your visit', correction: 'Flag something inaccurate in our info' }[t];
                return (
                  <button key={t} onClick={() => pick(t)} className="gw-press" style={{
                    display: 'flex', alignItems: 'center', gap: 14, padding: 16, borderRadius: 16, cursor: 'pointer',
                    background: T.white, border: `1px solid ${T.line}`, textAlign: 'left', boxShadow: '0 4px 14px rgba(16,40,66,0.05)',
                  }}>
                    <div style={{ width: 48, height: 48, borderRadius: 13, background: c.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <Icon name={c.icon} size={23} color={c.color} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontFamily: SANS, fontWeight: 800, fontSize: 16, color: T.ink }}>{c.label}</div>
                      <div style={{ fontFamily: SANS, fontSize: 13, color: T.muted, marginTop: 2, lineHeight: 1.35 }}>{desc}</div>
                    </div>
                    <Icon name="chevron-right" size={20} color={T.muted} />
                  </button>
                );
              })}
            </div>
          )}

          {/* Step 2 — form */}
          {step === 2 && <DraftForm type={type} draft={draft} set={setDraft} place={place} />}

          {/* Step 3 — review */}
          {step === 3 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div>
                <FieldLabel>Preview</FieldLabel>
                <ContributionCard item={preview} aiLearning={true} />
              </div>
              <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 16, padding: 16 }}>
                <div style={{ fontFamily: SANS, fontWeight: 800, fontSize: 14.5, color: T.ink, marginBottom: 12 }}>How this helps</div>
                {[
                  ['users', `Visible to travelers viewing ${place.name}`],
                  ['sparkle', "Reviewed, then used to improve this place's AI guide"],
                  ['award', `Earns you +${POINTS[type]} contributor points`],
                ].map((r, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: i ? 12 : 0 }}>
                    <div style={{ width: 34, height: 34, borderRadius: 10, background: T.tealBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                      <Icon name={r[0]} size={17} color={T.teal} />
                    </div>
                    <span style={{ fontFamily: SANS, fontSize: 13.5, color: T.body, fontWeight: 600, lineHeight: 1.35 }}>{r[1]}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* footer */}
      {step > 1 && (
        <div style={{ flexShrink: 0, padding: '13px 22px 20px', borderTop: `1px solid ${T.line}`, background: T.cream }}>
          {step === 2 ? (
            <button disabled={!ok} onClick={() => setStep(3)} style={{ width: '100%', padding: 16, borderRadius: 15, border: 'none', cursor: ok ? 'pointer' : 'default', background: ok ? T.navy : '#cfd8d4', color: '#fff', fontFamily: SANS, fontWeight: 800, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              Continue<Icon name="arrow-right" size={18} color="#fff" />
            </button>
          ) : (
            <button onClick={() => onSubmit(preview)} className="gw-press" style={{ width: '100%', padding: 16, borderRadius: 15, border: 'none', cursor: 'pointer', background: T.navy, color: '#fff', fontFamily: SANS, fontWeight: 800, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              Post contribution<Icon name="send" size={17} color="#fff" />
            </button>
          )}
        </div>
      )}
    </div>
  );
}

/* ═══ Variant 3 — AI interview (conversational) ═══ */
function AIComposer({ place, initialType, onClose, onSubmit }) {
  const [msgs, setMsgs] = React.useState([
    { from: 'ai', text: `Sours dei, ${HM.ME.name.split(' ')[1] || HM.ME.name}! 👋 You just explored ${place.name}. In a word — how was it?` },
    { from: 'ai', widget: 'rate' },
  ]);
  const [phase, setPhase] = React.useState('rate'); // rate → tell → typing → preview
  const [rating, setRating] = React.useState(0);
  const [text, setText] = React.useState('');
  const [input, setInput] = React.useState('');
  const scrollRef = React.useRef(null);

  React.useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [msgs, phase]);

  const push = (m) => setMsgs((x) => [...x, m]);

  const chooseRating = (n) => {
    setRating(n);
    const word = ['', 'Disappointing', 'Poor', 'Mixed', 'Good', 'Amazing'][n];
    setMsgs((x) => x.filter((m) => m.widget !== 'rate').concat([{ from: 'me', text: '★'.repeat(n) + `  ${word}` }]));
    setPhase('tell');
    setTimeout(() => push({ from: 'ai', text: "Love that. Now tell me what stood out — and if you know any history, a legend, or a detail most visitors miss, share it here. I'll shape it into something worth posting." }), 500);
  };

  const send = () => {
    if (input.trim().length < 3) return;
    const val = input.trim(); setText(val); setInput('');
    push({ from: 'me', text: val });
    setPhase('typing');
    push({ from: 'ai', widget: 'typing' });
    setTimeout(() => {
      setMsgs((x) => x.filter((m) => m.widget !== 'typing').concat([
        { from: 'ai', text: "Beautiful — thank you. I've polished that into a review and I'll add anything historical to this place's AI guide, credited to you. Here's your draft:" },
        { from: 'ai', widget: 'preview' },
      ]));
      setPhase('preview');
    }, 1500);
  };

  const draftItem = buildItem('review', { rating, sub: { value: 0, crowds: 0, safety: 0 }, text, photos: [] });

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 70, background: T.cream, display: 'flex', flexDirection: 'column' }} className="gw-sheet-in">
      {/* header */}
      <div style={{ background: T.navy, paddingBottom: 14, flexShrink: 0 }}>
        <StatusBar light />
        <div style={{ padding: '2px 18px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ width: 44, height: 44, borderRadius: 999, background: 'rgba(207,154,53,0.16)', border: `1px solid ${T.gold}66`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="sparkle" size={22} color={T.gold} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: SANS, fontWeight: 800, fontSize: 16, color: '#fff' }}>GoWithMe AI</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontFamily: SANS, fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>
              <span style={{ width: 7, height: 7, borderRadius: 999, background: '#4ac07a' }} />Helping you contribute
            </div>
          </div>
          <button onClick={onClose} style={{ width: 38, height: 38, borderRadius: 11, background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="x" size={18} color="#fff" />
          </button>
        </div>
      </div>

      {/* transcript */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '18px 18px 10px', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {msgs.map((m, i) => {
          if (m.widget === 'rate') return <div key={i} style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 16, borderBottomLeftRadius: 4, padding: 16, alignSelf: 'flex-start', maxWidth: '90%' }}>
            <div style={{ fontFamily: SANS, fontSize: 13, fontWeight: 700, color: T.muted, marginBottom: 10 }}>Tap to rate</div>
            <StarInput value={rating} onChange={chooseRating} size={34} />
          </div>;
          if (m.widget === 'typing') return <div key={i} style={{ alignSelf: 'flex-start', background: T.white, border: `1px solid ${T.line}`, borderRadius: 16, borderBottomLeftRadius: 4, padding: '14px 16px', display: 'flex', gap: 5 }}>
            {[0, 1, 2].map((d) => <span key={d} style={{ width: 7, height: 7, borderRadius: 999, background: T.muted, animation: 'blink 1.2s infinite', animationDelay: `${d * 0.18}s` }} />)}
          </div>;
          if (m.widget === 'preview') return <div key={i} style={{ alignSelf: 'stretch' }}><ContributionCard item={draftItem} aiLearning={true} /></div>;
          const ai = m.from === 'ai';
          return (
            <div key={i} style={{ alignSelf: ai ? 'flex-start' : 'flex-end', maxWidth: '86%' }}>
              <div style={{ padding: '11px 15px', borderRadius: 17, background: ai ? T.white : T.navy, color: ai ? T.body : '#fff', border: ai ? `1px solid ${T.line}` : 'none', borderBottomLeftRadius: ai ? 4 : 17, borderBottomRightRadius: ai ? 17 : 4, fontFamily: SANS, fontSize: 14.5, lineHeight: 1.5, textWrap: 'pretty' }}>{m.text}</div>
            </div>
          );
        })}
      </div>

      {/* input / actions */}
      <div style={{ flexShrink: 0, padding: '12px 18px 20px', borderTop: `1px solid ${T.line}`, background: T.cream }}>
        {phase === 'preview' ? (
          <div style={{ display: 'flex', gap: 11 }}>
            <button onClick={onClose} style={{ padding: '15px 18px', borderRadius: 15, border: `1.5px solid ${T.line}`, background: T.white, cursor: 'pointer', fontFamily: SANS, fontWeight: 700, fontSize: 15, color: T.body }}>Discard</button>
            <button onClick={() => onSubmit(draftItem)} className="gw-press" style={{ flex: 1, padding: 15, borderRadius: 15, border: 'none', cursor: 'pointer', background: T.navy, color: '#fff', fontFamily: SANS, fontWeight: 800, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
              Post it<Icon name="send" size={17} color="#fff" />
            </button>
          </div>
        ) : (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10 }}>
            <textarea value={input} onChange={(e) => setInput(e.target.value)} disabled={phase !== 'tell'} rows={1}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder={phase === 'rate' ? 'Rate above to start…' : phase === 'typing' ? 'GoWithMe is drafting…' : 'Tell me about your visit…'}
              style={{ flex: 1, border: `1px solid ${T.line}`, borderRadius: 16, background: phase === 'tell' ? T.white : '#eee7d8', padding: '13px 15px', fontFamily: SANS, fontSize: 15, color: T.ink, resize: 'none', outline: 'none', maxHeight: 90, boxSizing: 'border-box' }} />
            <button onClick={send} disabled={phase !== 'tell' || input.trim().length < 3} style={{ width: 48, height: 48, borderRadius: 999, border: 'none', flexShrink: 0, cursor: phase === 'tell' ? 'pointer' : 'default', background: phase === 'tell' && input.trim().length >= 3 ? T.gold : '#cfd8d4', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="send" size={20} color="#fff" />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

/* ═══ success overlay (shared) ═══ */
function PostSuccess({ type, place, onClose }) {
  const pts = POINTS[type] || 40;
  const learns = type === 'story' || type === 'tip' || type === 'correction';
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 80, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 26 }}>
      <div className="gw-back-in" style={{ position: 'absolute', inset: 0, background: 'rgba(8,18,32,0.62)', backdropFilter: 'blur(3px)' }} />
      <div className="gw-toast-in" style={{ position: 'relative', width: '100%', background: T.card, borderRadius: 26, padding: '30px 24px 24px', textAlign: 'center', boxShadow: '0 30px 60px rgba(0,0,0,0.4)' }}>
        <div style={{ width: 74, height: 74, borderRadius: 999, background: T.tealBg, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
          <Icon name="check" size={38} color={T.teal} strokeWidth={2.6} />
        </div>
        <h2 style={{ fontFamily: DISP, fontWeight: 800, fontSize: 26, color: T.ink, margin: 0 }}>Posted — thank you!</h2>
        <p style={{ fontFamily: SANS, fontSize: 14.5, lineHeight: 1.55, color: T.body, margin: '10px 0 0', textWrap: 'pretty' }}>
          Your {HM.CTYPES[type].label.toLowerCase()} is live on {place.name}.{' '}
          {learns ? "It's now being reviewed by GoWithMe AI to improve this place's guide for every traveler." : 'Thanks for helping fellow travelers explore with confidence.'}
        </p>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, margin: '18px 0 4px', padding: '10px 18px', borderRadius: 999, background: T.goldBg, border: `1px solid ${T.gold}55` }}>
          <Icon name="award" size={19} color={T.goldDk} />
          <span style={{ fontFamily: SANS, fontWeight: 800, fontSize: 15, color: T.goldDk }}>+{pts} contributor points</span>
        </div>
        <button onClick={onClose} className="gw-press" style={{ width: '100%', marginTop: 18, padding: 16, borderRadius: 15, border: 'none', cursor: 'pointer', background: T.navy, color: '#fff', fontFamily: SANS, fontWeight: 800, fontSize: 16 }}>Done</button>
      </div>
    </div>
  );
}

/* ═══ wrapper — picks the variant, shows success on submit ═══ */
function Composer({ place, initialType, variant, onClose, onSubmit }) {
  const [doneType, setDoneType] = React.useState(null);
  const submit = (item) => { onSubmit(item); setDoneType(item.type); };
  if (doneType) return <PostSuccess type={doneType} place={place} onClose={onClose} />;
  const props = { place, initialType, onClose, onSubmit: submit };
  if (variant === 'guided') return <GuidedComposer {...props} />;
  if (variant === 'ai') return <AIComposer {...props} />;
  return <QuickComposer {...props} />;
}

Object.assign(window, { Composer, QuickComposer, GuidedComposer, AIComposer, PostSuccess, DraftForm });
