// Pocket Marshal — Home screen + shared composer

// Composer: text input + camera + send. Used big on Home, compact in Chat.
function PMComposer({ theme, placeholder, onSend, big, autoFocus, prefill, onPrefillConsumed }) {
  const [text, setText] = React.useState('');
  const [photo, setPhoto] = React.useState(null); // dataURL
  const [photoErr, setPhotoErr] = React.useState(null);
  const [listening, setListening] = React.useState(false);
  const fileRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const recRef = React.useRef(null);
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;

  React.useEffect(() => {
    if (prefill) {
      setText(prefill);
      onPrefillConsumed && onPrefillConsumed();
      requestAnimationFrame(() => {
        if (inputRef.current) {
          inputRef.current.focus();
          inputRef.current.setSelectionRange(prefill.length, prefill.length);
        }
      });
    }
  }, [prefill]);

  const canSend = text.trim().length > 0 || photo;

  // Keep the textarea tall enough for its content — including a wrapped placeholder
  React.useLayoutEffect(() => {
    const el = inputRef.current;
    if (!el) return;
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 140) + 'px';
  }, [text, big]);
  const send = () => {
    if (!canSend) return;
    onSend({ text: text.trim(), photo });
    setText(''); setPhoto(null);
  };
  const pickPhoto = async (e) => {
    const f = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!f) return;
    setPhotoErr(null);
    try {
      setPhoto(await pmFileToThumb(f));
    } catch (err) {
      setPhoto(null);
      setPhotoErr("That photo format didn't load — try a JPG or PNG, or take a screenshot of it.");
    }
  };

  const toggleMic = () => {
    if (listening) {
      try { recRef.current && recRef.current.stop(); } catch (e) { /* noop */ }
      setListening(false);
      return;
    }
    try {
      const rec = new SR();
      rec.lang = 'en-US';
      rec.interimResults = false;
      rec.continuous = false;
      rec.onresult = (ev) => {
        const said = Array.from(ev.results).map((r) => r[0].transcript).join(' ').trim();
        if (said) setText((cur) => (cur ? cur.replace(/\s+$/, '') + ' ' : '') + said);
      };
      rec.onend = () => setListening(false);
      rec.onerror = () => setListening(false);
      recRef.current = rec;
      rec.start();
      setListening(true);
    } catch (e) { setListening(false); }
  };

  const btn = big ? 56 : 48;
  return (
    <div>
      {photoErr && (
        <p style={{ margin: '0 0 8px', color: theme.dangerInk || '#8c1c0e', fontWeight: 650, fontSize: '0.85em' }}>{photoErr}</p>
      )}
      {photo && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
          <div style={{ position: 'relative' }}>
            <img src={photo} alt="Attached photo" style={{ width: 72, height: 72, objectFit: 'cover', borderRadius: 10, border: `2px solid ${theme.line}`, display: 'block' }} />
            <button onClick={() => setPhoto(null)} aria-label="Remove photo" style={{
              position: 'absolute', top: -14, right: -14, width: 44, height: 44, borderRadius: '50%',
              background: 'transparent', border: 'none', display: 'grid', placeItems: 'center', cursor: 'pointer', padding: 0,
            }}>
              <span aria-hidden="true" style={{
                width: 28, height: 28, borderRadius: '50%', background: theme.flame, color: '#fff',
                border: `2px solid ${theme.paper}`, display: 'grid', placeItems: 'center',
              }}><IconX size={14} stroke={2.6} /></span>
            </button>
          </div>
          <span style={{ fontSize: '0.85em', color: theme.muted, fontWeight: 600 }}>Marshal will take a look at this</span>
        </div>
      )}
      <div style={{
        display: 'flex', alignItems: 'flex-end', gap: 8,
        background: theme.paper, border: `2px solid ${theme.line}`, borderRadius: big ? 18 : 16,
        padding: 8, boxShadow: big ? '0 2px 10px rgba(26,46,74,0.07)' : 'none',
        transition: 'border-color 0.15s',
      }}
        onFocusCapture={(e) => { e.currentTarget.style.borderColor = theme.focusRing; }}
        onBlurCapture={(e) => { e.currentTarget.style.borderColor = theme.line; }}>
        <textarea
          ref={inputRef}
          rows={1}
          value={text}
          autoFocus={autoFocus}
          placeholder={placeholder}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
          style={{
            flex: 1, resize: 'none', border: 'none', outline: 'none', background: 'transparent',
            font: 'inherit', fontSize: big ? '1.06em' : '1em', lineHeight: 1.4, color: theme.ink,
            padding: big ? '14px 8px' : '11px 8px', minHeight: btn, boxSizing: 'border-box',
          }} />
        <input ref={fileRef} type="file" accept="image/*" capture="environment" onChange={pickPhoto} style={{ display: 'none' }} />
        {SR && (
          <button onClick={toggleMic} aria-label={listening ? 'Stop listening' : 'Speak instead of typing'} style={{
            width: btn, height: btn, borderRadius: 12, border: 'none', cursor: 'pointer',
            background: listening ? '#fbe9e7' : theme.navySoft,
            color: listening ? '#b3362f' : theme.ink,
            display: 'grid', placeItems: 'center', flexShrink: 0, transition: 'background 0.15s',
          }}><IconMic size={big ? 26 : 23} style={listening ? { animation: 'pm-bounce 1.2s infinite ease-in-out' } : undefined} /></button>
        )}
        <button onClick={() => fileRef.current.click()} aria-label="Add a photo for Marshal to analyze" style={{
          width: btn, height: btn, borderRadius: 12, border: 'none', cursor: 'pointer',
          background: theme.emberSoft, color: theme.emberDark,
          display: 'grid', placeItems: 'center', flexShrink: 0,
        }}><IconCamera size={big ? 26 : 23} /></button>
        <button onClick={send} aria-label="Send" disabled={!canSend} style={{
          width: btn, height: btn, borderRadius: 12, border: 'none',
          cursor: canSend ? 'pointer' : 'default',
          background: canSend ? theme.cta : theme.navySoft,
          color: canSend ? theme.ctaInk : theme.muted,
          display: 'grid', placeItems: 'center', flexShrink: 0, transition: 'background 0.15s',
        }}><IconSend size={big ? 26 : 23} stroke={2.4} /></button>
      </div>
    </div>
  );
}

const PM_CHIPS = [
  { id: 'egress', label: 'Exit & egress', icon: IconDoor, prefill: 'Exit & egress issue: ' },
  { id: 'sprinkler', label: 'Sprinkler system', icon: IconDroplet, prefill: 'Sprinkler system: ' },
  { id: 'extinguisher', label: 'Fire extinguisher', icon: IconExtinguisher, prefill: 'Fire extinguisher: ' },
  { id: 'electrical', label: 'Electrical hazard', icon: IconBolt, prefill: 'Electrical hazard: ' },
];

function PMHome({ theme, t, inspectorName, sessions, onOpenSession, onSend, onChip, prefill, onPrefillConsumed }) {
  const recent = React.useMemo(() => (sessions || []).slice()
    .sort((a, b) => (b.time || 0) - (a.time || 0)).slice(0, 3), [sessions]);
  const hour = new Date().getHours();
  const daypart = hour < 12 ? 'Good morning' : hour < 17 ? 'Good afternoon' : 'Good evening';
  const shadow = '0 1px 2px rgba(36,48,64,0.04), 0 8px 28px rgba(36,48,64,0.07)';
  return (
    <div data-screen-label="Home" style={{ display: 'flex', flexDirection: 'column', minHeight: '100%', padding: '0 24px', boxSizing: 'border-box' }}>
      <div style={{ flex: 1.1 }} />
      <div style={{ maxWidth: 620, width: '100%', margin: '0 auto', textAlign: 'center' }}>
        <div style={{ display: 'inline-block', marginBottom: 6 }}>
          <MarshalAvatar styleKind={t.avatar} size={t.avatar === 'mascot' ? 84 : 56} float={t.avatar === 'mascot'} />
        </div>
        <div style={{ fontSize: '0.88em', fontWeight: 600, color: theme.muted, letterSpacing: '0.01em', marginTop: 14 }}>
          {daypart} — I'm Marshal
        </div>
        <h1 style={{ margin: '6px 0 26px', fontSize: '2.1em', lineHeight: 1.14, fontWeight: 700, color: theme.ink, letterSpacing: '-0.022em', textWrap: 'balance' }}>
          Hey {inspectorName}, what are you looking at today?
        </h1>

        <div style={{ textAlign: 'left' }}>
          <PMComposer theme={theme} big placeholder="Describe what you're seeing..."
            onSend={onSend} prefill={prefill} onPrefillConsumed={onPrefillConsumed} shadow={shadow} />
        </div>

        <div style={{
          display: 'grid', gap: 8, marginTop: 22,
          gridTemplateColumns: 'repeat(auto-fit, minmax(128px, 1fr))',
        }}>
          {PM_CHIPS.map((c) => {
            const Ic = c.icon;
            return (
              <button key={c.id} onClick={() => onChip(c)} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                background: theme.paper, border: `1px solid ${theme.cardEdge}`, borderRadius: 12,
                padding: '11px 10px', minHeight: 48, cursor: 'pointer', boxShadow: shadow,
                font: 'inherit', fontSize: '0.86em', fontWeight: 600, color: theme.ink, textAlign: 'left',
                whiteSpace: 'nowrap',
                transition: 'transform 0.15s, box-shadow 0.15s',
              }}
                onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.transform = 'none'; }}>
                <span style={{ color: theme.chipIcon, display: 'grid', placeItems: 'center', flexShrink: 0 }}><Ic size={19} /></span>
                {c.label}
              </button>
            );
          })}
        </div>

        <button onClick={() => onSend({ text: "Walk me through this inspection — I just arrived on site." })} style={{
          display: 'flex', alignItems: 'center', gap: 13, width: '100%', boxSizing: 'border-box',
          marginTop: 10, padding: '14px 16px', minHeight: 64,
          background: theme.paper, border: `1px solid ${theme.cardEdge}`, borderRadius: 14,
          font: 'inherit', textAlign: 'left', cursor: 'pointer', boxShadow: shadow,
          transition: 'transform 0.15s',
        }}
          onMouseEnter={(e) => { e.currentTarget.style.transform = 'translateY(-1px)'; }}
          onMouseLeave={(e) => { e.currentTarget.style.transform = 'none'; }}>
          <span style={{
            width: 40, height: 40, borderRadius: 11, background: theme.navySoft, color: theme.heroAccent,
            display: 'grid', placeItems: 'center', flexShrink: 0,
          }}><IconRoute size={23} /></span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{ display: 'block', fontWeight: 700, color: theme.ink, fontSize: '0.97em' }}>Walk me through an inspection</span>
            <span style={{ display: 'block', color: theme.muted, fontWeight: 500, fontSize: '0.82em', marginTop: 2, lineHeight: 1.35 }}>
              Marshal guides you area by area, tailored to the building
            </span>
          </span>
          <span style={{ color: theme.muted, display: 'grid', placeItems: 'center' }}><IconChevron size={19} /></span>
        </button>
      </div>

      {recent.length > 0 && (
        <div style={{ width: '100%', maxWidth: 520, margin: '20px auto 0' }}>
        <span style={{ display: 'block', fontSize: '0.7em', fontWeight: 800, letterSpacing: '0.08em', textTransform: 'uppercase', color: theme.muted, marginBottom: 7 }}>Pick back up</span>
        <button onClick={() => onOpenSession && onOpenSession(recent[0].id)} style={{
          display: 'flex', alignItems: 'center', gap: 10, width: '100%',
          boxSizing: 'border-box',
          background: 'transparent', border: `1px dashed ${theme.line}`, borderRadius: 11,
          padding: '9px 13px', minHeight: 48, cursor: 'pointer', font: 'inherit', textAlign: 'left',
        }}>
          <span style={{ color: theme.muted, display: 'grid', placeItems: 'center', flexShrink: 0 }}><IconRoute size={17} /></span>
          <span style={{ flex: 1, minWidth: 0 }}>
            <span style={{
              display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              fontWeight: 700, color: theme.ink, fontSize: '0.87em',
            }}>{recent[0].title}</span>
            <span style={{ display: 'block', color: theme.muted, fontWeight: 600, fontSize: '0.73em', marginTop: 1 }}>
              {pmTimeAgo(recent[0].time)}
            </span>
          </span>
          <span style={{ color: theme.muted, display: 'grid', placeItems: 'center', flexShrink: 0, opacity: 0.7 }}><IconChevron size={17} /></span>
        </button>
        </div>
      )}

      <div style={{ flex: 1.5, minHeight: 20 }} />
      <p style={{ textAlign: 'center', color: theme.muted, fontSize: '0.78em', fontWeight: 500, margin: '0 0 14px', opacity: 0.85 }}>
        Marshal cites the Florida Fire Prevention Code &amp; NFPA. The AHJ always has the final say.
      </p>
    </div>
  );
}

Object.assign(window, { PMComposer, PMHome, PM_CHIPS });
