// Step 2 — Listing: a live Google Play pre-lander mockup with click-to-edit fields.
// This is the centerpiece of the flow — what you see is what gets deployed.

const { useState: useS2, useRef: useR2, useEffect: useE2 } = React;

// Inline-editable text. Click to edit, blur or Enter to save.
const Editable = ({ value, onChange, multiline, placeholder, style, charLimit, mono, asInput }) => {
  const [editing, setEditing] = useS2(false);
  const [draft, setDraft] = useS2(value);
  const [hover, setHover] = useS2(false);
  useE2(() => setDraft(value), [value]);

  const commit = () => {
    setEditing(false);
    if (draft !== value) onChange(draft);
  };
  const cancel = () => { setDraft(value); setEditing(false); };

  if (editing) {
    const sharedStyle = {
      background: 'rgba(0,208,132,0.18)',
      border: '1px solid rgba(0,208,132,0.5)',
      borderRadius: 4,
      padding: '1px 5px',
      margin: '-2px -6px',
      color: 'inherit',
      font: 'inherit',
      width: 'calc(100% + 12px)',
      outline: 'none',
      ...style,
    };
    if (multiline) {
      return (
        <textarea
          autoFocus
          value={draft}
          maxLength={charLimit}
          onChange={e => setDraft(e.target.value)}
          onBlur={commit}
          onKeyDown={e => { if (e.key === 'Escape') cancel(); }}
          rows={Math.max(2, (draft || '').split('\n').length)}
          style={{ ...sharedStyle, resize: 'none', display: 'block', minHeight: 'auto' }}
        />
      );
    }
    return (
      <input
        autoFocus
        value={draft}
        maxLength={charLimit}
        onChange={e => setDraft(e.target.value)}
        onBlur={commit}
        onKeyDown={e => {
          if (e.key === 'Enter') commit();
          if (e.key === 'Escape') cancel();
        }}
        style={sharedStyle}
      />
    );
  }

  return (
    <span
      onClick={() => setEditing(true)}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        cursor: 'text',
        borderRadius: 4,
        padding: '0 4px',
        margin: '0 -4px',
        outline: hover ? '1px dashed rgba(0,208,132,0.55)' : '1px dashed transparent',
        transition: 'outline-color 0.12s',
        whiteSpace: multiline ? 'pre-wrap' : undefined,
        display: multiline ? 'block' : 'inline',
        fontFamily: mono ? 'JetBrains Mono, monospace' : undefined,
        ...style,
      }}>
      {value || <em style={{ color: 'rgba(0,0,0,0.4)' }}>{placeholder}</em>}
    </span>
  );
};

// Star row, click-to-set 1-5
const StarRow = ({ value, onChange, color = '#01875f', size = 12 }) => {
  return (
    <span style={{ color, fontSize: size, letterSpacing: 0.5, cursor: onChange ? 'pointer' : 'default' }}>
      {[1,2,3,4,5].map(n => (
        <span key={n}
          onClick={onChange ? () => onChange(n) : undefined}
          style={{ padding: '0 1px' }}>
          {n <= value ? '★' : '☆'}
        </span>
      ))}
    </span>
  );
};

// Compact emoji-picker popover
const IconPicker = ({ value, onChange, onClose }) => {
  return (
    <div style={{
      position: 'absolute', top: 76, left: 18, zIndex: 50,
      background: '#fff', border: '1px solid #dadce0',
      borderRadius: 10, padding: 10,
      boxShadow: '0 12px 32px rgba(0,0,0,0.18)',
      display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 4,
      width: 220,
    }}>
      {window.ICON_CHOICES.map(ic => (
        <button key={ic}
          onClick={() => { onChange(ic); onClose(); }}
          style={{
            aspectRatio: '1', fontSize: 22, padding: 0,
            background: value === ic ? '#e6f4ea' : '#fff',
            border: `1px solid ${value === ic ? '#01875f' : '#e8eaed'}`,
            borderRadius: 6,
            cursor: 'pointer',
          }}>{ic}</button>
      ))}
    </div>
  );
};

const Step2Listing = ({ draft, setDraft }) => {
  const { SectionTitle, ICON_CHOICES } = window;
  const [iconOpen, setIconOpen] = useS2(false);

  const set = (k, v) => setDraft({ ...draft, [k]: v });

  const updateReview = (idx, patch) => {
    const reviews = [...draft.reviews];
    reviews[idx] = { ...reviews[idx], ...patch };
    setDraft({ ...draft, reviews });
  };
  const deleteReview = (idx) => {
    setDraft({ ...draft, reviews: draft.reviews.filter((_, i) => i !== idx) });
  };
  const addReview = () => {
    setDraft({ ...draft, reviews: [...draft.reviews, { name: 'New User', date: 'just now', rating: 5, text: 'Click to edit this review.' }] });
  };

  const updateScreenshot = (idx, val) => {
    const ss = [...draft.screenshots];
    ss[idx] = val;
    setDraft({ ...draft, screenshots: ss });
  };

  // Distribution for bars - keep static
  const dist = [78, 14, 5, 2, 1];

  return (
    <div className="step-anim">
      <SectionTitle
        kicker="Step 02 / 07"
        title="Build your store listing"
        desc="This is the actual Google Play screen users see before they install. Click anything in the preview to edit it — name, reviews, screenshots, copy. Changes go live with the rest of the config."
      />

      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.05fr) minmax(0,1fr)', gap: 22, alignItems: 'flex-start' }}>
        {/* === Pre-lander mockup === */}
        <div>
          <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginBottom: 10, paddingLeft: 4, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', animation: 'pulse 1.6s ease-in-out infinite' }}></span>
            Live preview — click any element to edit
          </div>

          <PhoneFrame>
            {/* Google Play top bar */}
            <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px', background: '#fff', borderBottom: '1px solid #f1f3f4', fontSize: 14 }}>
              <span style={{ marginRight: 16, color: '#5f6368', fontSize: 20 }}>←</span>
              <span style={{ flex: 1, color: '#5f6368', fontSize: 13 }}>Apps</span>
              <span style={{ color: '#5f6368', fontSize: 18 }}>🔍</span>
            </div>

            {/* App header */}
            <div style={{ position: 'relative', padding: 16, display: 'flex', gap: 14 }}>
              <div
                onClick={() => setIconOpen(true)}
                style={{
                  width: 72, height: 72, borderRadius: 18,
                  background: 'linear-gradient(135deg, #ff00ff, #00ffff)',
                  display: 'grid', placeItems: 'center', fontSize: 36,
                  boxShadow: '0 2px 6px rgba(0,0,0,0.12)',
                  cursor: 'pointer', flexShrink: 0,
                  outline: '2px dashed transparent',
                }}
                onMouseEnter={e => e.currentTarget.style.outline = '2px dashed rgba(0,208,132,0.55)'}
                onMouseLeave={e => e.currentTarget.style.outline = '2px dashed transparent'}
              >{draft.icon}</div>

              <div style={{ flex: 1, minWidth: 0, color: '#202124' }}>
                <h1 style={{ fontSize: 22, fontWeight: 400, lineHeight: 1.2, marginBottom: 4, color: '#202124' }}>
                  <Editable value={draft.name} onChange={(v) => set('name', v)} placeholder="App name" charLimit={50} />
                </h1>
                <div style={{ color: '#01875f', fontSize: 14, fontWeight: 500, marginBottom: 2 }}>
                  <Editable value={draft.developer} onChange={(v) => set('developer', v)} placeholder="Developer name" charLimit={40} />
                </div>
                <div style={{ color: '#5f6368', fontSize: 12 }}>
                  {draft.containsAds ? 'Contains ads · In-app purchases' : 'In-app purchases'}
                </div>
              </div>

              {iconOpen && <IconPicker value={draft.icon} onChange={(v) => set('icon', v)} onClose={() => setIconOpen(false)} />}
            </div>

            {/* Stats row */}
            <div style={{ display: 'flex', padding: '16px 8px', borderBottom: '1px solid #f1f3f4', borderTop: '1px solid #f1f3f4' }}>
              <Stat
                value={
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                    <Editable value={String(draft.rating)} onChange={(v) => set('rating', parseFloat(v) || 0)} charLimit={4} />
                    <span style={{ fontSize: 10 }}>★</span>
                  </span>
                }
                label={
                  <Editable
                    value={draft.ratingCount.toLocaleString() + ' reviews'}
                    onChange={(v) => {
                      const n = parseInt(v.replace(/[^\d]/g, '')) || 0;
                      set('ratingCount', n);
                    }} charLimit={20}
                  />
                }
              />
              <Divider />
              <Stat
                value={<Editable value={draft.downloads} onChange={(v) => set('downloads', v)} charLimit={10} />}
                label="Downloads"
              />
              <Divider />
              <Stat
                value={<span style={{ display: 'inline-block' }}>🛡</span>}
                label={<Editable value={draft.ageRating} onChange={(v) => set('ageRating', v)} charLimit={20} />}
              />
            </div>

            {/* Install button */}
            <div style={{ padding: 16 }}>
              <button style={{
                width: '100%', padding: 12,
                background: '#01875f', color: '#fff', border: 'none',
                borderRadius: 4, fontSize: 14, fontWeight: 500,
                letterSpacing: 0.5, textTransform: 'uppercase',
                cursor: 'pointer',
              }}>Install</button>
            </div>

            {/* Device availability */}
            <div style={{ display: 'flex', justifyContent: 'center', gap: 8, padding: '12px 16px', color: '#5f6368', fontSize: 13, borderBottom: '1px solid #f1f3f4' }}>
              <span>📱</span> This app is available for your device
            </div>

            {/* Screenshots row */}
            <div style={{ display: 'flex', gap: 8, padding: 16, overflowX: 'auto', borderBottom: '1px solid #f1f3f4' }}>
              {draft.screenshots.map((ss, i) => (
                <div key={i} style={{
                  width: 150, height: 267, borderRadius: 8, flexShrink: 0,
                  background: `linear-gradient(160deg, ${['#1a0033', '#2a1a4a', '#0a3a5a', '#3a1a6a'][i % 4]}, #003366)`,
                  display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                  color: '#ff00ff', fontSize: 13, padding: 12, textAlign: 'center',
                  boxShadow: '0 1px 3px rgba(0,0,0,0.12)',
                  position: 'relative',
                }}>
                  <div style={{ color: '#fff', fontWeight: 600 }}>
                    <Editable value={ss} onChange={(v) => updateScreenshot(i, v)} charLimit={28} style={{ color: '#fff' }} />
                  </div>
                  <div style={{ position: 'absolute', bottom: 6, right: 8, fontSize: 9, color: 'rgba(255,255,255,0.4)', fontFamily: 'JetBrains Mono, monospace' }}>#{i + 1}</div>
                </div>
              ))}
            </div>

            {/* About */}
            <Section title="About this game">
              <Editable value={draft.aboutText} onChange={(v) => set('aboutText', v)} multiline charLimit={500} placeholder="Describe the app…" />
            </Section>

            {/* Ratings & reviews */}
            <Section title="Ratings and reviews">
              <div style={{ display: 'flex', gap: 24, alignItems: 'center', marginBottom: 16 }}>
                <div>
                  <div style={{ fontSize: 48, fontWeight: 300, color: '#202124', lineHeight: 1 }}>{draft.rating}</div>
                  <StarRow value={Math.round(draft.rating)} size={14} />
                  <div style={{ color: '#5f6368', fontSize: 12 }}>{draft.ratingCount.toLocaleString()}</div>
                </div>
                <div style={{ flex: 1 }}>
                  {dist.map((pct, i) => (
                    <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, height: 10, marginBottom: 4 }}>
                      <span style={{ fontSize: 11, color: '#5f6368', width: 8 }}>{5 - i}</span>
                      <div style={{ flex: 1, height: 4, background: '#e8eaed', borderRadius: 2, overflow: 'hidden' }}>
                        <div style={{ height: '100%', width: `${pct}%`, background: '#01875f' }}></div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Reviews list */}
              {draft.reviews.map((r, i) => (
                <ReviewBlock key={i}
                  review={r}
                  onChange={(patch) => updateReview(i, patch)}
                  onDelete={() => deleteReview(i)}
                />
              ))}

              <button onClick={addReview} style={{
                width: '100%', padding: 12, marginTop: 8,
                background: 'transparent', color: '#01875f',
                border: '1px dashed #01875f', borderRadius: 6,
                fontSize: 13, fontWeight: 500, cursor: 'pointer',
              }}>+ Add a review</button>
            </Section>

            {/* What's new */}
            <Section title="What's new" last>
              <Editable value={draft.whatsNewText} onChange={(v) => set('whatsNewText', v)} multiline charLimit={400} placeholder="Release notes…" />
            </Section>
          </PhoneFrame>
        </div>

        {/* === Side panel: technical fields === */}
        <div style={{ position: 'sticky', top: 88 }}>
          <div className="panel" style={{ padding: 22, marginBottom: 14 }}>
            <div className="panel-head">
              <h2>App config</h2>
              <span style={{ fontSize: 10.5, color: 'var(--muted)', fontFamily: 'JetBrains Mono, monospace', background: 'var(--bg-3)', padding: '2px 7px', borderRadius: 4, textTransform: 'uppercase', letterSpacing: '0.05em' }}>internal</span>
            </div>

            <div className="field">
              <label>App ID</label>
              <input
                className="mono"
                type="text"
                value={draft.id}
                onChange={e => setDraft({ ...draft, id: e.target.value })}
                disabled={!!draft._editing}
                placeholder={draft.type === 'pwa' ? 'pwa.your-name' : 'app.your-name'}
              />
              <div className="help">Used in worker URL — never changes.</div>
            </div>

            <div className="field">
              <label>Domain <span className="opt">— optional</span></label>
              <input
                className="mono"
                type="text"
                value={draft.domain}
                onChange={e => setDraft({ ...draft, domain: e.target.value })}
                placeholder={`${window.slugify(draft.name) || 'your-name'}.pages.dev`}
              />
            </div>

            <div className="field" style={{ marginBottom: 0 }}>
              <label>Internal note</label>
              <textarea
                value={draft.note}
                rows={2}
                onChange={e => setDraft({ ...draft, note: e.target.value })}
                placeholder="Reminder for yourself — not visible to users"
              />
            </div>
          </div>

          <div className="panel" style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
              <window.Toggle on={draft.containsAds} onChange={(v) => set('containsAds', v)} />
              <div style={{ fontSize: 13, fontWeight: 500 }}>Contains ads label</div>
            </div>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>Required by Play Store policy if the app shows third-party ads.</div>
          </div>

          <div style={{
            marginTop: 14, padding: '12px 14px',
            background: 'var(--accent-dim)', border: '1px solid var(--accent-line)',
            borderRadius: 9, fontSize: 12, color: 'var(--text-dim)',
            display: 'flex', alignItems: 'flex-start', gap: 10,
          }}>
            <window.IconCheck size={15} style={{ color: 'var(--accent)', flexShrink: 0, marginTop: 1 }} />
            <span>
              <strong style={{ color: 'var(--text)' }}>Pro tip:</strong>{' '}
              Reviews and screenshots both impact install rate. Aim for 8-12 reviews mixing 4 and 5 stars, with at least 2 in the user's language.
            </span>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Helpers used above ──────────────────────────────────────────────────

const PhoneFrame = ({ children }) => (
  <div style={{
    width: '100%',
    background: '#fff',
    border: '1px solid var(--line)',
    borderRadius: 14,
    overflow: 'hidden',
    color: '#202124',
    fontFamily: 'Roboto, Helvetica Neue, Arial, sans-serif',
    fontSize: 14,
    lineHeight: 1.5,
    boxShadow: '0 16px 40px -16px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.04) inset',
  }}>{children}</div>
);

const Section = ({ title, last, children }) => (
  <div style={{ padding: '24px 16px', borderBottom: last ? 'none' : '1px solid #f1f3f4' }}>
    <h2 style={{ fontSize: 16, fontWeight: 500, color: '#202124', marginBottom: 12 }}>{title}</h2>
    <div style={{ color: '#5f6368', fontSize: 14, lineHeight: 1.55 }}>{children}</div>
  </div>
);

const Stat = ({ value, label }) => (
  <div style={{ flex: 1, textAlign: 'center', padding: '4px 8px' }}>
    <div style={{ fontSize: 14, fontWeight: 500, color: '#202124' }}>{value}</div>
    <div style={{ fontSize: 11, color: '#5f6368', marginTop: 2 }}>{label}</div>
  </div>
);

const Divider = () => <div style={{ width: 1, background: '#e8eaed', margin: '4px 0' }}></div>;

const ReviewBlock = ({ review, onChange, onDelete }) => {
  const [showActions, setShowActions] = useS2(false);
  return (
    <div
      style={{ padding: '16px 0', borderBottom: '1px solid #f1f3f4', position: 'relative' }}
      onMouseEnter={() => setShowActions(true)}
      onMouseLeave={() => setShowActions(false)}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
        <div style={{
          width: 32, height: 32, borderRadius: '50%',
          background: '#01875f', color: '#fff',
          display: 'grid', placeItems: 'center',
          fontWeight: 500, fontSize: 14,
        }}>{(review.name || '?').charAt(0).toUpperCase()}</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 500, color: '#202124' }}>
            <Editable value={review.name} onChange={(v) => onChange({ name: v })} charLimit={30} />
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
            <StarRow value={review.rating} onChange={(n) => onChange({ rating: n })} />
          </div>
        </div>
        <div style={{ fontSize: 12, color: '#5f6368' }}>
          <Editable value={review.date} onChange={(v) => onChange({ date: v })} charLimit={20} />
        </div>
        {showActions && (
          <button onClick={onDelete} style={{
            position: 'absolute', top: 12, right: -4,
            background: '#fff', border: '1px solid #e8eaed', borderRadius: 5,
            padding: '3px 7px', cursor: 'pointer', fontSize: 11, color: '#d93025',
          }}>Delete</button>
        )}
      </div>
      <div style={{ color: '#202124', fontSize: 14, lineHeight: 1.5 }}>
        <Editable value={review.text} onChange={(v) => onChange({ text: v })} multiline charLimit={300} />
      </div>
    </div>
  );
};

window.Step2Identity = Step2Listing;
window.Step2Listing = Step2Listing;
