/* ============================================================================
   MOWDEW — Review capture at peak trust
   Fired right after a great Visit Recap (balanced water + good photos). Forks
   by SENTIMENT to protect the business's public rating:
     THUMBS-UP   → one-tap to the owner's Google / Apple Maps review (Sprout celebrates)
     THUMBS-DOWN → a PRIVATE fix-it note to the owner first (calm, apologetic)
   Warm, never desperate, hard rate-limited. Reuses the kit. Loads after the
   recap; exposed on window.
   ========================================================================= */

/* owner config (session) — enabled, review URL, frequency, monthly cap */
function reviewCfg() {
  return (window.__reviewCfg = window.__reviewCfg || {
    on: true, url: 'g.page/marta-lawn-pool/review', freq: '4 great visits', cap: 12, used: 5,
  });
}

/* ─── ReviewCapture — the sentiment fork (homeowner, below the recap) ── */
function ReviewCapture({ proName = 'Diego', nameHidden = false }) {
  const cfg = reviewCfg();
  const [step, setStep] = React.useState('ask'); // ask | happy | shared | private | sent | dismissed
  const [reason, setReason] = React.useState('');
  const who = nameHidden ? 'your pro' : proName;
  if (!cfg.on || step === 'dismissed') return null;

  // ASK — tasteful, dismissible, rate-limit reassurance
  if (step === 'ask') {
    return (
      <div className="card" style={{ padding: 15, borderColor: 'var(--green-100)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Sprout size={48} mood="happy" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, letterSpacing: '-0.02em' }}>Happy with {who}'s work?</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 2 }}>Balanced water, clean pool — looked like a good one.</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 9, marginTop: 13 }}>
          <button onClick={() => setStep('happy')} className="btn btn-primary" style={{ flex: 1, minHeight: 46 }}><Icon name="thumbs-up" size={18} />Yes, great</button>
          <button onClick={() => setStep('private')} className="btn btn-secondary" style={{ flex: 1, minHeight: 46 }}><Icon name="thumbs-down" size={18} />Not really</button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 11 }}>
          <span style={{ fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '.04em', color: 'var(--ink-400,#A8A498)' }}>WE ASK SPARINGLY · ONCE IN A WHILE</span>
          <button onClick={() => setStep('dismissed')} style={{ border: 'none', background: 'none', color: 'var(--ink-500)', fontSize: 12, fontWeight: 700, cursor: 'pointer', padding: '4px 6px' }}>Maybe later</button>
        </div>
      </div>
    );
  }

  // HAPPY — one tap to the public review
  if (step === 'happy') {
    return (
      <div className="card" style={{ padding: 16, borderColor: 'var(--green-100)', background: 'var(--green-50)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
          <Sprout size={58} mood="happy" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17, letterSpacing: '-0.02em' }}>Love to hear it!</div>
            <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 2, lineHeight: 1.45 }}>A quick public review helps {who} reach more neighbors. Takes 20 seconds.</div>
          </div>
        </div>
        <button onClick={() => setStep('shared')} className="btn btn-primary btn-block" style={{ minHeight: 48, marginTop: 13 }}>
          <span style={{ width: 20, height: 20, borderRadius: 5, background: '#fff', display: 'grid', placeItems: 'center', flexShrink: 0 }}><span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13, color: '#4285F4' }}>G</span></span>
          Rate {who} on Google
        </button>
        <button onClick={() => setStep('shared')} className="btn btn-secondary btn-block" style={{ minHeight: 44, marginTop: 9 }}><Icon name="pin" size={17} />Leave it on Apple Maps</button>
        <button onClick={() => setStep('dismissed')} style={{ border: 'none', background: 'none', color: 'var(--ink-500)', fontSize: 12, fontWeight: 700, cursor: 'pointer', padding: '10px 6px 0', display: 'block', margin: '0 auto' }}>No thanks</button>
      </div>
    );
  }

  // SHARED — gratitude
  if (step === 'shared') {
    return (
      <div className="card" style={{ padding: 16, borderColor: 'var(--green-100)', background: 'var(--green-50)', textAlign: 'center' }}>
        <Sprout size={72} mood="happy" />
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17, marginTop: 6 }}>Thank you!</div>
        <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 4, lineHeight: 1.45, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>It means the world to {who} — and helps a small local business grow.</div>
      </div>
    );
  }

  // PRIVATE — deflect into a fix-it conversation
  if (step === 'private') {
    const chips = ['Missed a spot', 'Running late', 'Communication', 'Water still off'];
    return (
      <div className="card" style={{ padding: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <Dewy size={48} mood="wink" />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, letterSpacing: '-0.02em' }}>Sorry it wasn't great</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)', marginTop: 2 }}>Tell {who} what went wrong — this goes straight to them, privately.</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, margin: '13px 0 11px' }}>
          {chips.map(ch => (
            <button key={ch} onClick={() => setReason(r => r === ch ? '' : ch)} style={{ padding: '8px 12px', borderRadius: 99, border: reason === ch ? '2px solid var(--green-500)' : '1.5px solid var(--ink-200)', background: reason === ch ? 'var(--green-50)' : '#fff', color: reason === ch ? 'var(--green-800)' : 'var(--ink-700)', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>{ch}</button>
          ))}
        </div>
        <textarea className="input" rows={3} placeholder={`What could ${who} do better?`} defaultValue="" style={{ resize: 'none', lineHeight: 1.5 }} />
        <button onClick={() => setStep('sent')} className="btn btn-primary btn-block" style={{ minHeight: 48, marginTop: 12 }}><Icon name="send" size={18} />Send privately to {who}</button>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, marginTop: 10, fontSize: 11.5, color: 'var(--ink-500)' }}><Icon name="lock" size={13} />Stays between you and {who} — never posted publicly.</div>
      </div>
    );
  }

  // SENT — reassurance, fix-it framing
  return (
    <div className="card" style={{ padding: 16, textAlign: 'center' }}>
      <Dewy size={68} mood="happy" />
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 17, marginTop: 6 }}>Thanks — {who} will make it right</div>
      <div style={{ fontSize: 13, color: 'var(--ink-700)', marginTop: 4, lineHeight: 1.45, maxWidth: 290, marginLeft: 'auto', marginRight: 'auto' }}>We've passed this along privately. {nameHidden ? 'Your pro' : proName} reaches out personally — no need to chase it.</div>
    </div>
  );
}

/* ─── OWNER · review-requests settings card (used on the o_reviews screen) ─ */
function OwnerReviewSettingsCard({ toast }) {
  const cfg = reviewCfg();
  const [on, setOn] = React.useState(cfg.on);
  const [url, setUrl] = React.useState(cfg.url);
  const [freq, setFreq] = React.useState(cfg.freq);
  const FREQS = ['Every visit', '4 great visits', 'Monthly'];
  return (
    <div className="card" style={{ padding: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <span style={{ width: 42, height: 42, borderRadius: 12, background: 'var(--green-50)', display: 'grid', placeItems: 'center', color: 'var(--green-700)', flexShrink: 0 }}><Icon name="star" size={21} /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 16, letterSpacing: '-0.02em' }}>Review requests</div>
          <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>Ask happy customers, after a great visit</div>
        </div>
        <Toggle on={on} onChange={() => { setOn(v => { cfg.on = !v; return !v; }); }} tone="green" />
      </div>
      {on && (
        <>
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 7 }}>Your Google / Maps review link</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, border: '1.5px solid var(--ink-200)', borderRadius: 'var(--radius-md)', padding: '0 12px' }}>
              <Icon name="external" size={16} style={{ color: 'var(--ink-400,#A8A498)', flexShrink: 0 }} />
              <input value={url} onChange={e => { setUrl(e.target.value); cfg.url = e.target.value; }} style={{ flex: 1, border: 'none', outline: 'none', padding: '12px 0', fontFamily: 'var(--font-mono)', fontSize: 12.5, background: 'transparent', minWidth: 0 }} />
            </div>
          </div>
          <div style={{ marginTop: 14 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-700)', marginBottom: 7 }}>How often to ask</div>
            <div style={{ display: 'flex', gap: 7 }}>
              {FREQS.map(f => (
                <button key={f} onClick={() => { setFreq(f); cfg.freq = f; }} style={{ flex: 1, padding: '10px 6px', borderRadius: 11, border: freq === f ? '2px solid var(--green-500)' : '1.5px solid var(--ink-200)', background: freq === f ? 'var(--green-50)' : '#fff', color: freq === f ? 'var(--green-800)' : 'var(--ink-700)', fontSize: 12, fontWeight: 700, cursor: 'pointer' }}>{f}</button>
              ))}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginTop: 14, padding: '11px 13px', background: 'var(--aqua-50)', borderRadius: 12, fontSize: 12, color: 'var(--ink-700)', lineHeight: 1.45 }}>
            <Icon name="shield" size={15} style={{ color: 'var(--aqua-700)', flexShrink: 0, marginTop: 1 }} />
            Only thumbs-up customers see the public link. Anything less comes to you <b>privately</b> first — so you fix it before it ever hits your rating.
          </div>
        </>
      )}
    </div>
  );
}

/* ─── OWNER · tiny dashboard stat ───────────────────────────────────── */
function OwnerReviewStat({ onClick }) {
  const cfg = reviewCfg();
  const left = Math.max(0, cfg.cap - cfg.used);
  return (
    <div onClick={onClick} className="card" style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 11, cursor: onClick ? 'pointer' : 'default' }}>
      <span style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--green-50)', display: 'grid', placeItems: 'center', color: 'var(--green-700)', flexShrink: 0 }}><Icon name="star" size={18} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 13.5 }}>{cfg.used} review asks this month</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>{left} left · {cfg.freq.toLowerCase()} cadence</div>
      </div>
      {onClick && <Icon name="chevron-right" size={17} style={{ color: 'var(--ink-300)', flexShrink: 0 }} />}
    </div>
  );
}

/* ─── OWNER · review settings screen ────────────────────────────────── */
function OwnerReviewsM({ go, toast }) {
  return (
    <Screen padBottom={26} footer={
      <ActionBar><button onClick={() => { toast && toast('Review settings saved', 'green'); go('o_settings'); }} className="btn btn-primary btn-lg btn-block"><Icon name="check-circle" size={20} />Save</button></ActionBar>}>
      <TopBar title="Reviews" subtitle="Turn great visits into public love" onBack={() => go('o_settings')} />
      <div style={{ padding: '4px 18px 0' }}>
        <OwnerReviewStat />
      </div>
      <div style={{ padding: '14px 18px 0' }}>
        <SectionHead tone="green" icon="star" style={{ marginBottom: 10 }}>Ask settings</SectionHead>
        <OwnerReviewSettingsCard toast={toast} />
      </div>
      <div style={{ padding: '14px 18px 0' }}>
        <div className="card" style={{ padding: 13, display: 'flex', alignItems: 'center', gap: 11, background: 'var(--green-50)', borderColor: 'var(--green-100)' }}>
          <Sprout size={42} mood="happy" />
          <div style={{ flex: 1, fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.45 }}>Warm, never desperate — Mowdew only asks after a genuinely good visit, and never nags.</div>
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { reviewCfg, ReviewCapture, OwnerReviewSettingsCard, OwnerReviewStat, OwnerReviewsM });
