/* ============================================================================
   MOWDEW LIVE DEMO — "Approve before work" (the 5th synchronized flow)
   Homeowner snaps a photo + request → owner turns it into a PRICED quote →
   homeowner APPROVES the exact price → it lands on the pro's route. The
   photo and price carry across all three phones via the shared `world.req`.
     null → requested → quoted → scheduled   (+ declined)
   World/actions/tracker/hints live in Mowdew Live Demo.html; the per-phone
   UI lives here and is mounted from the demo phone shells.
   ========================================================================= */

/* the canned quote the owner sends (keeps the demo one-tap) */
const DEMO_QUOTE = {
  lines: [{ label: 'Waterline tile descale', cents: 14000 }, { label: 'Acid spot-treat', cents: 4000 }],
  total: 18000,
  note: 'I can knock this out on your next visit — about 90 min, all-in.',
};
const DEMO_REQ = { photo: 'pool-before', desc: 'The waterline tile looks scaled — white crust along the edge.' };

/* ─── HOMEOWNER · the request lifecycle card (sits on the visit feed) ── */
function HomeRequestCard({ world, act, openReq }) {
  const s = world.req;
  // idle — the invitation to request work
  if (!s || s === 'declined') {
    return (
      <div style={{ padding: '10px 18px 0' }}>
        <div className="card" style={{ padding: 14, borderColor: 'var(--aqua-100)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
            <span style={{ width: 40, height: 40, borderRadius: 11, background: 'var(--aqua-50)', display: 'grid', placeItems: 'center', color: 'var(--aqua-700)', flexShrink: 0 }}><Icon name="camera" size={20} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14 }}>Something need fixing?</div>
              <div style={{ fontSize: 12, color: 'var(--ink-500)' }}>{s === 'declined' ? 'Declined — nothing was scheduled or billed.' : 'Snap it · Diego quotes · you approve the price'}</div>
            </div>
          </div>
          <button onClick={openReq} className="btn btn-secondary btn-block" style={{ minHeight: 44, marginTop: 12 }}><Icon name="camera" size={17} />Request work with a photo</button>
        </div>
      </div>
    );
  }
  return (
    <div style={{ padding: '10px 18px 0' }}>
      <div className="card" style={{ padding: 14, borderColor: s === 'quoted' ? 'var(--aqua-200,#8FD3DF)' : s === 'scheduled' ? 'var(--green-100)' : 'var(--ink-100)', boxShadow: s === 'quoted' ? '0 0 0 3px var(--aqua-50), var(--shadow-md)' : 'var(--shadow-sm)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 11 }}>
          <PaperAvatar who="owner" size={34} />
          <div style={{ flex: 1, minWidth: 0, fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Marta Lawn &amp; Pool</div>
          {s === 'requested' && <DmMark tone="aqua" pulse>SENT</DmMark>}
          {s === 'quoted' && <DmMark tone="aqua" pulse>QUOTE IN</DmMark>}
          {s === 'scheduled' && <DmMark tone="green">APPROVED</DmMark>}
        </div>
        {/* the photo + ask, carried through */}
        <div style={{ display: 'flex', gap: 11, alignItems: 'center' }}>
          <PhotoTile scene={DEMO_REQ.photo} height={48} radius={11} style={{ width: 60, flexShrink: 0 }} />
          <div style={{ fontSize: 12.5, color: 'var(--ink-700)', lineHeight: 1.4 }}>"{DEMO_REQ.desc}"</div>
        </div>

        {s === 'requested' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, background: 'var(--ink-50)', borderRadius: 11, padding: '10px 12px', fontSize: 12.5, color: 'var(--ink-600,#6E6B60)' }}>
            <span className="tn-pulse" style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--aqua-500)', flexShrink: 0 }} />Diego's reviewing your photo — a quote is on the way.
          </div>
        )}

        {(s === 'quoted' || s === 'scheduled') && (
          <div style={{ marginTop: 12, background: 'var(--paper)', border: '1px solid var(--ink-100)', borderRadius: 13, padding: 13 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
              <Icon name="invoice" size={15} style={{ color: 'var(--aqua-700)' }} /><span style={{ fontWeight: 700, fontSize: 13 }}>Diego's quote</span>
            </div>
            {DEMO_QUOTE.lines.map((l, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0', color: 'var(--ink-700)' }}><span>{l.label}</span><span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{fmtMoney(l.cents)}</span></div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--ink-100)' }}>
              <span style={{ fontWeight: 700, fontSize: 13.5 }}>Total</span><Amount cents={DEMO_QUOTE.total} size={18} />
            </div>
            {DEMO_QUOTE.note && <div style={{ fontSize: 12, color: 'var(--ink-500)', marginTop: 9, lineHeight: 1.45, fontStyle: 'italic' }}>"{DEMO_QUOTE.note}"</div>}
          </div>
        )}

        {s === 'quoted' && (
          <div style={{ display: 'flex', gap: 8, marginTop: 11 }}>
            <button onClick={act.homeApproveQuote} className="btn btn-primary" style={{ flex: 1.6, minHeight: 46 }}><Icon name="check" size={17} />Approve · {fmtMoney(DEMO_QUOTE.total)}</button>
            <button onClick={act.homeDeclineQuote} className="btn btn-secondary" style={{ flex: 1, minHeight: 46 }}>Decline</button>
          </div>
        )}
        {s === 'quoted' && <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 9, fontSize: 11.5, color: 'var(--ink-500)' }}><Icon name="shield" size={13} style={{ color: 'var(--blue-700)', flexShrink: 0 }} />You approve the exact price before anyone shows up.</div>}
        {s === 'scheduled' && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 11, background: 'var(--green-50)', borderRadius: 11, padding: '10px 12px', fontSize: 12.5, fontWeight: 600, color: 'var(--green-800)' }}>
            <Icon name="check-circle" size={15} style={{ flexShrink: 0 }} />Approved at {fmtMoney(DEMO_QUOTE.total)} — added to your next visit. It only bills once it's done.
          </div>
        )}
      </div>
    </div>
  );
}

/* ─── HOMEOWNER · compose sheet (photo + description) ───────────────── */
function HomeRequestSheet({ open, onClose, act }) {
  const [photo, setPhoto] = React.useState(false);
  const [desc, setDesc] = React.useState('The waterline tile looks scaled');
  const send = () => { onClose && onClose(); act.homeRequestWork(); setTimeout(() => { setPhoto(false); }, 300); };
  const quick = ['The waterline tile looks scaled', 'Pump sounds rough', 'Water looks cloudy'];
  return (
    <Sheet open={open} onClose={onClose} title="Request work">
      <div style={{ fontSize: 13, color: 'var(--ink-500)', marginTop: -6, marginBottom: 13 }}>Goes to Diego with your photo. He sends a priced quote — nothing happens until you approve it.</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 12 }}>
        <span style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--aqua-50)', display: 'grid', placeItems: 'center', color: 'var(--aqua-700)', flexShrink: 0 }}><Icon name="droplet" size={19} /></span>
        <div><div style={{ fontWeight: 700, fontSize: 13.5 }}>88 Crestline Ave · pool</div><div style={{ fontSize: 11.5, color: 'var(--ink-500)' }}>Diego Marta · your pro</div></div>
      </div>
      <button onClick={() => setPhoto(true)} style={{ width: '100%', minHeight: 96, borderRadius: 'var(--radius-lg)', border: photo ? '1.5px solid var(--aqua-200,#8FD3DF)' : '1.5px dashed var(--ink-200)', background: photo ? 'var(--aqua-50)' : '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, color: photo ? 'var(--aqua-700)' : 'var(--ink-500)', marginBottom: 12 }}>
        {photo ? <><Icon name="check-circle" size={22} /><span style={{ fontWeight: 700, fontSize: 14 }}>Photo attached</span></> : <><Icon name="camera" size={24} /><span style={{ fontWeight: 700, fontSize: 14 }}>Attach a photo</span></>}
      </button>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 14 }}>
        {quick.map(q => <button key={q} onClick={() => setDesc(q)} style={{ padding: '8px 12px', borderRadius: 99, border: desc === q ? '2px solid var(--aqua-500)' : '1.5px solid var(--ink-200)', background: desc === q ? 'var(--aqua-50)' : '#fff', color: desc === q ? 'var(--aqua-700)' : 'var(--ink-700)', fontSize: 12.5, fontWeight: 700, cursor: 'pointer' }}>{q}</button>)}
      </div>
      <button onClick={send} className="btn btn-primary btn-block" style={{ minHeight: 48 }}><Icon name="send" size={18} />Send to Diego</button>
    </Sheet>
  );
}

/* ─── OWNER · request → make-a-quote card (sits in the Inbox tab) ────── */
function OwnerRequestCard({ world, act }) {
  const s = world.req;
  if (!s || s === 'declined') {
    if (s === 'declined') {
      return (
        <div style={{ padding: '14px 18px 0' }}>
          <SectionHead tone="aqua" icon="camera" style={{ marginBottom: 10 }} meta="from a customer">Requests</SectionHead>
          <div className="card" style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
            <Icon name="x" size={16} style={{ color: 'var(--ink-400,#A8A498)', flexShrink: 0 }} />
            <div style={{ fontSize: 12.5, color: 'var(--ink-500)' }}>Emma declined your quote — nothing was scheduled.</div>
          </div>
        </div>
      );
    }
    return null;
  }
  return (
    <div style={{ padding: '14px 18px 0' }}>
      <SectionHead tone="aqua" icon="camera" style={{ marginBottom: 10 }} meta={s === 'requested' ? 'needs a quote' : 'from a customer'}>Requests</SectionHead>
      <div className="card" style={{ padding: 14, borderColor: s === 'requested' ? 'var(--yellow-100)' : s === 'scheduled' ? 'var(--green-100)' : 'var(--ink-100)', boxShadow: s === 'requested' ? '0 0 0 3px var(--yellow-50), var(--shadow-md)' : 'var(--shadow-sm)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 11 }}>
          <PaperAvatar who="home" size={34} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 700, fontSize: 13.5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Emma Walsh · Crestline pool</div>
            <div style={{ fontSize: 11, color: 'var(--ink-500)' }}>Customer ask · just now</div>
          </div>
          {s === 'requested' && <DmMark tone="yellow" pulse>NEEDS YOU</DmMark>}
          {s === 'quoted' && <DmMark tone="aqua" pulse>WAITING ON EMMA</DmMark>}
          {s === 'scheduled' && <DmMark tone="green">APPROVED</DmMark>}
        </div>
        <div style={{ position: 'relative' }}>
          <PhotoTile scene={DEMO_REQ.photo} height={120} radius="var(--radius-lg)" />
          <span style={{ position: 'absolute', bottom: 9, left: 9, fontFamily: 'var(--font-mono)', fontSize: 9.5, fontWeight: 700, letterSpacing: '.05em', color: '#fff', background: 'rgba(27,26,23,.6)', padding: '4px 8px', borderRadius: 7 }}>PHOTO · FROM EMMA</span>
        </div>
        <div style={{ fontSize: 13, color: 'var(--ink-700)', lineHeight: 1.45, marginTop: 10 }}>"{DEMO_REQ.desc}"</div>

        {(s === 'quoted' || s === 'scheduled') && (
          <div style={{ marginTop: 12, background: 'var(--paper)', border: '1px solid var(--ink-100)', borderRadius: 13, padding: 13 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 8 }}>
              <Icon name="invoice" size={15} style={{ color: 'var(--aqua-700)' }} /><span style={{ fontWeight: 700, fontSize: 13 }}>Your quote</span>
            </div>
            {DEMO_QUOTE.lines.map((l, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, padding: '4px 0', color: 'var(--ink-700)' }}><span>{l.label}</span><span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{fmtMoney(l.cents)}</span></div>
            ))}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 8, paddingTop: 8, borderTop: '1px solid var(--ink-100)' }}>
              <span style={{ fontWeight: 700, fontSize: 13.5 }}>Total Emma approves</span><Amount cents={DEMO_QUOTE.total} size={18} />
            </div>
          </div>
        )}

        <div style={{ marginTop: 12 }}>
          {s === 'requested' && <button onClick={act.ownerSendQuote} className="btn btn-primary btn-block" style={{ minHeight: 46 }}><Icon name="invoice" size={17} />Send a quote · {fmtMoney(DEMO_QUOTE.total)}</button>}
          {s === 'quoted' && <ReschedStatusBar state="waiting" text="Quote sent — waiting on Emma to approve the exact price." />}
          {s === 'scheduled' && <ReschedStatusBar state="approved" text={`Emma approved ${fmtMoney(DEMO_QUOTE.total)} — added to Marco's route at Crestline.`} />}
        </div>
      </div>
    </div>
  );
}

/* ─── PRO · the approved add-on, shown on the Crestline stop ─────────── */
function ProAddedWork({ world }) {
  if (world.req !== 'scheduled') return null;
  return (
    <div style={{ marginTop: 11, background: 'var(--green-50)', border: '1px solid var(--green-100)', borderRadius: 13, padding: '11px 13px', display: 'flex', alignItems: 'center', gap: 10 }}>
      <span style={{ width: 34, height: 34, borderRadius: 10, background: 'var(--green-700)', display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0 }}><Icon name="plus" size={17} strokeWidth={2.6} /></span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 700, fontSize: 13 }}>Added: tile descale + acid treat</div>
        <div style={{ fontSize: 11.5, color: 'var(--green-800)' }}>Customer-approved · price set by the office</div>
      </div>
      <Icon name="check-circle" size={18} style={{ color: 'var(--green-700)', flexShrink: 0 }} />
    </div>
  );
}

Object.assign(window, { DEMO_QUOTE, DEMO_REQ, HomeRequestCard, HomeRequestSheet, OwnerRequestCard, ProAddedWork });
