// Resident Portal — homepage hero. Search/navigate surface.
// Free-text composer routes dog-ish queries straight to the chat application;
// other queries surface a friendly placeholder noting that only the dog-license
// flow is wired up in this prototype.

function PortalHero({ initialQuery }) {
  const t = window.tokens;
  const [text, setText] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const [composerError, setComposerError] = React.useState('');
  const [unsupportedNote, setUnsupportedNote] = React.useState('');
  // True while the Get Started button is in its loading state, just before navigation.
  const [submitting, setSubmitting] = React.useState(false);

  const suggestions = [
    'Register my dog',
    'Apply for a permit',
    'Pay a parking ticket',
    'Renew my license',
  ];

  const goToApply = (echoQuery) => {
    // Button flips into a loading state while we navigate. Short, honest:
    // no splash, no morph, just a spinner on the action the user clicked.
    setSubmitting(true);
    setTimeout(() => {
      const qs = new URLSearchParams();
      if (echoQuery) qs.set('q', echoQuery);
      window.location.href = 'Resident Portal - Apply.html?' + qs.toString();
    }, 450);
  };

  const handleSubmit = (raw) => {
    const v = (raw ?? text).trim();
    if (!v) {
      setComposerError("Tell us what you need so we can point you in the right direction.");
      return;
    }
    setComposerError('');
    setUnsupportedNote('');
    const dogish = /\b(dog|puppy|pup|pet|canine|license|licence|tag|rabies|register)\b/i.test(v);
    if (dogish) {
      goToApply(v);
    } else {
      setUnsupportedNote("This is a prototype — only the dog-license flow is wired up. Try \"Register my dog\" to see it.");
    }
  };

  // Trigger from outside (e.g., suggestion chip on home, "Register a dog" tile)
  React.useEffect(() => {
    if (initialQuery) {
      setText(initialQuery);
      handleSubmit(initialQuery);
    }
    // eslint-disable-next-line
  }, [initialQuery]);

  const onKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmit(); }
  };

  const invalid = Boolean(composerError);
  const borderColor = invalid ? t.color.err : (focused ? t.color.action : t.color.strong);

  return (
    <section className="rp-hero" style={{
      width: '100%',
      maxWidth: 820,
      margin: '0 auto',
      padding: '96px 32px 72px',
    }}>
      <h1 style={{
        fontSize: t.size.displayXL,
        lineHeight: 1.1,
        fontWeight: 500,
        letterSpacing: '-0.044em',
        margin: '0 0 20px',
        color: t.color.text,
      }}>
        Tell us what you need.
        <br />
        <span style={{ color: t.color.muted }}>We'll take it from there.</span>
      </h1>

      <p style={{
        fontSize: 19,
        fontWeight: 400,
        lineHeight: 1.5,
        letterSpacing: '-0.1px',
        color: t.color.body,
        margin: '0 0 40px',
        maxWidth: 620,
      }}>
        Permits, licenses, payments, records. One place for every state and local service in New Jersey. Ask in your own words.
      </p>

      <div className="rp-composer" style={{
        background: t.color.bg,
        border: `1px solid ${borderColor}`,
        borderRadius: t.radius.xl,
        padding: 18,
        transition: 'border-color 120ms ease, box-shadow 120ms ease',
        boxShadow: invalid ? `0 0 0 1px ${t.color.err}` : (focused ? `0 0 0 1px ${t.color.action}` : 'none'),
      }}>
        <textarea
          value={text}
          placeholder="e.g. I need to register my dog…"
          onChange={(e) => { setText(e.target.value); if (composerError) setComposerError(''); if (unsupportedNote) setUnsupportedNote(''); }}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={onKeyDown}
          aria-invalid={invalid}
          rows={2}
          style={{
            display: 'block',
            width: '100%',
            minHeight: 56,
            background: 'transparent',
            border: 'none',
            outline: 'none',
            resize: 'none',
            fontFamily: t.font.sans,
            fontSize: 17,
            lineHeight: 1.55,
            color: t.color.text,
            padding: 0,
          }}
        />
        <div className="rp-composer-bar" style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 16,
          marginTop: 14,
          paddingTop: 14,
          borderTop: `1px solid ${t.color.hair}`,
        }}>
          <div className="rp-composer-suggestions" style={{
            display: 'flex',
            gap: 6,
            flex: 1,
            minWidth: 0,
            overflow: 'hidden',
            flexWrap: 'nowrap',
          }}>
            {suggestions.map((s) => (
              <button
                key={s}
                onClick={() => handleSubmit(s)}
                className="rp-suggestion"
                style={{
                  padding: '5px 12px',
                  background: t.color.paper,
                  border: `1px solid ${t.color.hair}`,
                  borderRadius: t.radius.pill,
                  fontFamily: t.font.sans,
                  fontSize: 13,
                  color: t.color.body,
                  cursor: 'pointer',
                  transition: 'all 120ms ease',
                  whiteSpace: 'nowrap',
                }}
              >
                {s}
              </button>
            ))}
          </div>
          <Button variant="primary" onClick={() => handleSubmit()} disabled={submitting}>
            {submitting ? (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                <span style={{
                  width: 14, height: 14, borderRadius: 7,
                  border: '2px solid rgba(255,255,255,0.35)',
                  borderTopColor: '#fff',
                  display: 'inline-block',
                  animation: 'rp-btn-spin 0.7s linear infinite',
                }} />
                <style>{`@keyframes rp-btn-spin { to { transform: rotate(360deg) } }`}</style>
                Loading…
              </span>
            ) : 'Get Started'}
          </Button>
        </div>
      </div>

      {composerError && (
        <div role="alert" style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 8,
          marginTop: 10,
          padding: '0 4px',
          fontSize: 13,
          color: t.color.err,
          fontFamily: t.font.sans,
        }}>
          <span aria-hidden="true" style={{
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            width: 16, height: 16,
            borderRadius: 8,
            background: t.color.err,
            color: '#fff',
            fontFamily: t.font.mono,
            fontSize: 11,
            fontWeight: 600,
            lineHeight: 1,
            flexShrink: 0,
          }}>!</span>
          {composerError}
        </div>
      )}

      {unsupportedNote && (
        <div role="status" style={{
          marginTop: 14,
          padding: '12px 16px',
          background: t.color.paper,
          border: `1px solid ${t.color.hair}`,
          borderRadius: t.radius.lg,
          fontSize: 14,
          lineHeight: 1.5,
          color: t.color.body,
          fontFamily: t.font.sans,
        }}>
          {unsupportedNote}
        </div>
      )}

      {/* (Removed: InlineMorphOverlay — the splash-style transition was the
          wrong call. The Get Started button now shows a brief loading state
          and we navigate.) */}
    </section>
  );
}

Object.assign(window, { PortalHero });
