/* ─── Walk View — Chat-style decision coaching interface ─── */
/* Mocks the conversational Walk product closer to the real MVP */

const WALK_STEPS = ['Frame', 'Tentative elements', 'Assumptions', 'Sufficient certainty', 'Implement + monitor'];

const MOCK_CONVERSATION = [
  {
    role: 'assistant',
    content: 'We\u2019ll walk one decision through five steps to sufficient certainty.\n\nWhat decision are you working on?',
  },
];

const WalkView = ({ onNavigate }) => {
  const [messages, setMessages] = React.useState(MOCK_CONVERSATION);
  const [input, setInput] = React.useState('');
  const [streaming, setStreaming] = React.useState(false);
  const [currentStep, setCurrentStep] = React.useState(0);
  const [showSidePanel, setShowSidePanel] = React.useState(true);
  const [walkComplete, setWalkComplete] = React.useState(false);
  const [showCheckout, setShowCheckout] = React.useState(false);
  const [paid, setPaid] = React.useState(false);
  const [email, setEmail] = React.useState('');
  const scrollRef = React.useRef(null);
  const taRef = React.useRef(null);
  const isMobile = useMediaQuery(900);

  /* Lock body scroll when modal is open */
  React.useEffect(() => {
    if (showCheckout) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [showCheckout]);

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages]);

  React.useEffect(() => {
    const ta = taRef.current;
    if (!ta) return;
    ta.style.height = 'auto';
    ta.style.height = Math.min(ta.scrollHeight, 180) + 'px';
  }, [input]);

  const simulateResponse = async (userMsg) => {
    setStreaming(true);

    /* Simple mock responses based on conversation length */
    const responses = [
      'Good. Let me help you think through that. First, let\u2019s get the Purpose clear.\n\nWhat is the organisation actually for? Not the mission statement\u2009\u2014\u2009what does it really exist to do?',
      'Thank you. And what is this specific decision an opportunity to do? Why is now the moment?',
      'That helps. Now, what outcome would you experience if this decision succeeds? Over what time period?',
      'Let\u2019s look at the context. Three bands matter here: the immediate situation, the organisational environment, and the wider forces you cannot control.\n\nStart with what is happening internally.',
      'Good. Now let\u2019s move to assumptions.\n\nWhat are the assumptions we are making here? Name everything this decision rests on.',
    ];

    const idx = Math.min(messages.length - 1, responses.length - 1);
    const text = responses[idx] || 'What else are you assuming? For each one, think about: how much does the outcome depend on it, and how confident are you?';

    /* Simulate typing */
    let acc = '';
    setMessages(m => [...m, { role: 'assistant', content: '' }]);
    for (let i = 0; i < text.length; i += 3) {
      acc = text.slice(0, i + 3);
      const snap = acc;
      await new Promise(r => setTimeout(r, 12));
      setMessages(m => {
        const copy = [...m];
        copy[copy.length - 1] = { role: 'assistant', content: snap };
        return copy;
      });
    }
    setMessages(m => {
      const copy = [...m];
      copy[copy.length - 1] = { role: 'assistant', content: text };
      return copy;
    });

    /* Advance step occasionally */
    if (messages.length >= 5 && currentStep < 1) setCurrentStep(1);
    if (messages.length >= 7 && currentStep < 2) setCurrentStep(2);
    if (messages.length >= 9 && currentStep < 3) setCurrentStep(3);
    if (messages.length >= 11 && currentStep < 4) { setCurrentStep(4); setWalkComplete(true); }

    setStreaming(false);
  };

  const send = () => {
    const text = input.trim();
    if (!text || streaming) return;
    const userMsg = { role: 'user', content: text };
    setMessages(m => [...m, userMsg]);
    setInput('');
    simulateResponse(userMsg);
  };

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

  const w = {
    wrapper: {
      height: '100vh',
      height: '100dvh',
      display: 'flex',
      flexDirection: 'column',
      background: 'var(--bg-primary)',
    },
    topBar: {
      borderBottom: '1px solid var(--border-light)',
      background: 'var(--bg-primary)',
      flexShrink: 0,
      padding: '0 var(--space-6)',
      paddingTop: 'var(--safe-top, 0px)',
      paddingLeft: 'calc(var(--space-6) + var(--safe-left, 0px))',
      paddingRight: 'calc(var(--space-6) + var(--safe-right, 0px))',
    },
    topInner: {
      maxWidth: '1100px',
      margin: '0 auto',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'space-between',
      height: '48px',
    },
    backLink: {
      fontFamily: 'var(--font-sans)',
      fontSize: '13px',
      color: 'var(--fg-tertiary)',
      cursor: 'pointer',
      background: 'none',
      border: 'none',
      padding: 0,
      display: 'flex',
      alignItems: 'center',
      gap: '6px',
      transition: 'color var(--duration-fast) var(--easing)',
    },
    stepCount: {
      fontFamily: 'var(--font-sans)',
      fontSize: '12px',
      fontWeight: 600,
      color: 'var(--fg-tertiary)',
      letterSpacing: '0.02em',
    },
    progress: {
      height: '2px',
      background: 'var(--border-light)',
    },
    progressFill: {
      height: '2px',
      background: 'var(--fg-primary)',
      transition: 'width 400ms ease-in-out',
    },
    main: {
      flex: 1,
      display: 'flex',
      overflow: 'hidden',
    },
    chatPane: {
      flex: 1,
      display: 'flex',
      flexDirection: 'column',
      minWidth: 0,
    },
    messages: {
      flex: 1,
      overflowY: 'auto',
      padding: isMobile ? 'var(--space-4) var(--space-4)' : 'var(--space-6)',
      paddingLeft: isMobile ? 'calc(var(--space-4) + var(--safe-left, 0px))' : 'var(--space-6)',
      paddingRight: isMobile ? 'calc(var(--space-4) + var(--safe-right, 0px))' : 'var(--space-6)',
      display: 'flex',
      flexDirection: 'column',
      gap: 'var(--space-5)',
      WebkitOverflowScrolling: 'touch',
    },
    msgAssistant: {
      maxWidth: isMobile ? '100%' : '680px',
      fontFamily: 'var(--font-serif)',
      fontSize: isMobile ? '16px' : '17px',
      lineHeight: 1.7,
      color: 'var(--fg-primary)',
      whiteSpace: 'pre-wrap',
      padding: 0,
    },
    msgUser: {
      maxWidth: isMobile ? '85%' : '680px',
      alignSelf: 'flex-end',
      background: 'var(--bg-secondary)',
      borderRadius: '8px',
      padding: 'var(--space-3) var(--space-4)',
      fontFamily: 'var(--font-serif)',
      fontSize: isMobile ? '15px' : '16px',
      lineHeight: 1.6,
      color: 'var(--fg-primary)',
      whiteSpace: 'pre-wrap',
    },
    inputBar: {
      borderTop: '1px solid var(--border-light)',
      padding: 'var(--space-4) var(--space-6)',
      paddingBottom: 'calc(var(--space-4) + var(--safe-bottom, 0px))',
      paddingLeft: 'calc(var(--space-6) + var(--safe-left, 0px))',
      paddingRight: 'calc(var(--space-6) + var(--safe-right, 0px))',
      background: 'var(--bg-primary)',
      flexShrink: 0,
    },
    inputWrap: {
      maxWidth: '680px',
      margin: '0 auto',
      display: 'flex',
      gap: 'var(--space-3)',
      alignItems: 'flex-end',
    },
    textarea: {
      flex: 1,
      fontFamily: 'var(--font-serif)',
      fontSize: '16px',
      lineHeight: 1.6,
      color: 'var(--fg-primary)',
      background: 'var(--bg-secondary)',
      border: '1px solid var(--border)',
      borderRadius: '8px',
      padding: 'var(--space-3) var(--space-4)',
      outline: 'none',
      resize: 'none',
      minHeight: '44px',
      transition: 'border-color var(--duration-fast) var(--easing)',
    },
    sendBtn: {
      fontFamily: 'var(--font-sans)',
      fontSize: '14px',
      fontWeight: 500,
      padding: '10px 20px',
      background: 'var(--fg-primary)',
      color: 'var(--bg-primary)',
      border: 'none',
      borderRadius: '8px',
      cursor: 'pointer',
      whiteSpace: 'nowrap',
      flexShrink: 0,
      height: '44px',
      transition: 'opacity var(--duration-fast) var(--easing)',
    },
    /* Side panel — Decision Record building */
    sidePanel: {
      width: '340px',
      borderLeft: '1px solid var(--border-light)',
      background: '#fff',
      overflowY: 'auto',
      padding: 'var(--space-6)',
      flexShrink: 0,
      display: 'flex',
      flexDirection: 'column',
      gap: 'var(--space-5)',
    },
    docLabel: {
      fontFamily: 'var(--font-sans)',
      fontSize: '10px',
      fontWeight: 600,
      letterSpacing: '0.08em',
      textTransform: 'uppercase',
      color: 'var(--fg-tertiary)',
      marginBottom: 'var(--space-1)',
      display: 'block',
    },
    docText: {
      fontFamily: 'var(--font-serif)',
      fontSize: '14px',
      lineHeight: 1.6,
      color: 'var(--fg-primary)',
      margin: 0,
    },
    docEmpty: {
      fontFamily: 'var(--font-serif)',
      fontSize: '13px',
      fontStyle: 'italic',
      color: 'var(--fg-tertiary)',
      margin: 0,
    },
    sidePanelToggle: {
      fontFamily: 'var(--font-sans)',
      fontSize: '12px',
      fontWeight: 500,
      color: 'var(--fg-tertiary)',
      background: 'none',
      border: '1px solid var(--border)',
      borderRadius: 'var(--btn-radius)',
      padding: '4px 12px',
      cursor: 'pointer',
      transition: 'border-color var(--duration-fast) var(--easing)',
    },
    /* Step indicators in toolbar */
    stepsBar: {
      display: 'flex',
      gap: '2px',
      alignItems: 'center',
      maxWidth: '1100px',
      margin: '0 auto',
      padding: '0 0 var(--space-2)',
    },
    stepPill: (active, done) => ({
      fontFamily: 'var(--font-sans)',
      fontSize: '10px',
      fontWeight: active ? 600 : 400,
      color: active ? 'var(--fg-primary)' : done ? 'var(--accent)' : 'var(--fg-tertiary)',
      padding: '3px 8px',
      borderRadius: '3px',
      background: active ? 'var(--bg-tertiary)' : 'transparent',
      whiteSpace: 'nowrap',
    }),
    stepDot: {
      width: '3px',
      height: '3px',
      borderRadius: '50%',
      background: 'var(--border)',
      flexShrink: 0,
    },
    /* Checkout modal — editorial register */
    overlay: {
      position: 'fixed',
      inset: 0,
      background: 'rgba(26,26,26,0.35)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 200,
      padding: isMobile ? 'var(--space-4)' : 'var(--space-6)',
      paddingTop: 'calc(var(--safe-top, 0px) + var(--space-4))',
      paddingBottom: 'calc(var(--safe-bottom, 0px) + var(--space-4))',
      overflowY: 'auto',
      WebkitOverflowScrolling: 'touch',
    },
    modal: {
      background: '#fffefa',
      border: '1px solid var(--border)',
      borderRadius: '3px',
      padding: isMobile ? 'var(--space-5)' : 'var(--space-7) var(--space-8)',
      maxWidth: '420px',
      width: '100%',
      display: 'flex',
      flexDirection: 'column',
      gap: 'var(--space-5)',
      boxShadow: '0 2px 12px rgba(26,26,26,0.08)',
      maxHeight: isMobile ? 'none' : '90vh',
      overflowY: 'auto',
    },
    modalTitle: {
      fontFamily: 'var(--font-serif)',
      fontSize: '20px',
      fontWeight: 500,
      color: 'var(--fg-primary)',
      margin: 0,
      lineHeight: 1.2,
    },
    modalDesc: {
      fontFamily: 'var(--font-serif)',
      fontSize: 'var(--text-sm)',
      color: 'var(--fg-secondary)',
      lineHeight: 'var(--leading-relaxed)',
      margin: 0,
    },
    modalInput: {
      fontFamily: 'var(--font-sans)',
      fontSize: '16px',
      padding: '12px 14px',
      border: '1px solid var(--border)',
      borderRadius: '3px',
      background: 'var(--bg-primary)',
      color: 'var(--fg-primary)',
      outline: 'none',
      width: '100%',
    },
    modalBtn: {
      fontFamily: 'var(--font-sans)',
      fontSize: '14px',
      fontWeight: 500,
      padding: '12px 24px',
      background: 'var(--fg-primary)',
      color: 'var(--bg-primary)',
      border: 'none',
      borderRadius: '3px',
      cursor: 'pointer',
      width: '100%',
    },
    modalGhost: {
      fontFamily: 'var(--font-sans)',
      fontSize: '13px',
      color: 'var(--fg-tertiary)',
      background: 'none',
      border: 'none',
      cursor: 'pointer',
      textAlign: 'center',
      padding: 0,
    },
    trustLine: {
      fontFamily: 'var(--font-sans)',
      fontSize: '11px',
      color: 'var(--fg-tertiary)',
      textAlign: 'center',
    },
    priceRow: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'baseline',
      padding: 'var(--space-3) 0',
      borderTop: '1px solid var(--border-light)',
      borderBottom: '1px solid var(--border-light)',
    },
    priceLabel: {
      fontFamily: 'var(--font-serif)',
      fontSize: '15px',
      color: 'var(--fg-primary)',
    },
    priceAmount: {
      fontFamily: 'var(--font-sans)',
      fontSize: '18px',
      fontWeight: 600,
      color: 'var(--fg-primary)',
    },
    cardInputRow: {
      display: 'flex',
      gap: 'var(--space-3)',
    },
    finishBar: {
      borderTop: '1px solid var(--border-light)',
      padding: 'var(--space-3) var(--space-4)',
      paddingLeft: 'calc(var(--space-4) + var(--safe-left, 0px))',
      paddingRight: 'calc(var(--space-4) + var(--safe-right, 0px))',
      background: 'var(--bg-secondary)',
      flexShrink: 0,
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      gap: 'var(--space-3)',
      flexWrap: 'wrap',
    },
    finishBtn: {
      fontFamily: 'var(--font-sans)',
      fontSize: isMobile ? '13px' : '14px',
      fontWeight: 500,
      padding: isMobile ? '8px 20px' : '10px 28px',
      background: 'var(--accent)',
      color: '#fff',
      border: 'none',
      borderRadius: 'var(--radius-md)',
      cursor: 'pointer',
      whiteSpace: 'nowrap',
    },
    finishHint: {
      fontFamily: 'var(--font-serif)',
      fontSize: isMobile ? '13px' : '14px',
      color: 'var(--fg-secondary)',
      fontStyle: 'italic',
    },
  };

  const progressPct = ((currentStep + 1) / WALK_STEPS.length) * 100;

  return React.createElement('div', { style: w.wrapper },
    /* ─── Top bar ─── */
    React.createElement('div', { style: w.topBar },
      React.createElement('div', { style: w.topInner },
        React.createElement('button', {
          style: w.backLink,
          onClick: () => onNavigate('home'),
        }, '\u2190 Exit Walk'),
        React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 'var(--space-3)' } },
          React.createElement('span', { style: w.stepCount },
            WALK_STEPS[currentStep]),
          !isMobile && React.createElement('button', {
            style: w.sidePanelToggle,
            onClick: () => setShowSidePanel(!showSidePanel),
          }, showSidePanel ? 'Hide document' : 'Show document'),
        ),
      ),
      React.createElement('div', { style: w.progress },
        React.createElement('div', { style: { ...w.progressFill, width: progressPct + '%' } }),
      ),
      !isMobile && React.createElement('div', { style: w.stepsBar },
        ...WALK_STEPS.flatMap((step, i) => {
          const items = [
            React.createElement('span', {
              key: 's' + i,
              style: w.stepPill(i === currentStep, i < currentStep),
            }, step),
          ];
          if (i < WALK_STEPS.length - 1) {
            items.push(React.createElement('span', { key: 'd' + i, style: w.stepDot }));
          }
          return items;
        }),
      ),
    ),

    /* ─── Main area ─── */
    React.createElement('div', { style: w.main },
      /* Chat pane */
      React.createElement('div', { style: w.chatPane },
        React.createElement('div', { ref: scrollRef, style: w.messages },
          ...messages.map((m, i) =>
            React.createElement('div', {
              key: i,
              style: m.role === 'user' ? w.msgUser : w.msgAssistant,
            }, m.content || (streaming && i === messages.length - 1 ? '\u2026' : '')),
          ),
        ),
        React.createElement('div', { style: w.inputBar },
          React.createElement('div', { style: w.inputWrap },
            React.createElement('textarea', {
              ref: taRef,
              value: input,
              onChange: (e) => setInput(e.target.value),
              onKeyDown: onKeyDown,
              rows: 1,
              placeholder: 'Type your reply\u2026',
              disabled: streaming,
              style: w.textarea,
            }),
            React.createElement('button', {
              onClick: send,
              disabled: streaming || !input.trim(),
              style: {
                ...w.sendBtn,
                opacity: (streaming || !input.trim()) ? 0.4 : 1,
                cursor: (streaming || !input.trim()) ? 'not-allowed' : 'pointer',
              },
            }, streaming ? 'Thinking\u2026' : 'Send'),
          ),
          React.createElement('div', {
            style: {
              maxWidth: '680px',
              margin: 'var(--space-2) auto 0',
              fontFamily: 'var(--font-sans)',
              fontSize: '11px',
              color: 'var(--fg-tertiary)',
              fontStyle: 'italic',
            }
          }, 'Preview build. Conversations are simulated.'),
        ),
        /* Finish bar — editorial close */
        walkComplete && React.createElement('div', { style: w.finishBar },
          React.createElement('span', { style: w.finishHint }, 'Your decision is on the record.'),
          React.createElement('button', {
            style: w.finishBtn,
            onClick: () => setShowCheckout(true),
          }, paid ? 'Download PDF' : 'Download the PDF \u2014 $39'),
        ),
      ),

      /* Side panel — Decision Record skeleton */
      !isMobile && showSidePanel && React.createElement('div', { style: w.sidePanel },
        React.createElement('div', { style: {
          borderBottom: '2px solid var(--fg-primary)',
          paddingBottom: 'var(--space-3)',
          marginBottom: 'var(--space-3)',
        }},
          React.createElement('span', { style: {
            fontFamily: 'var(--font-serif)',
            fontSize: '18px',
            fontWeight: 500,
            color: 'var(--fg-primary)',
          } }, 'Decision Record'),
          React.createElement('span', { style: {
            display: 'block',
            fontFamily: 'var(--font-sans)',
            fontSize: '11px',
            color: 'var(--fg-tertiary)',
            marginTop: '4px',
          } }, 'Builds as you talk'),
        ),
        ...WALK_STEPS.map((step, i) =>
          React.createElement('div', { key: i },
            React.createElement('span', { style: w.docLabel }, step),
            i <= currentStep
              ? React.createElement('p', { style: w.docEmpty }, 'Waiting for your input\u2026')
              : React.createElement('p', { style: { ...w.docEmpty, color: 'var(--border)' } }, '\u2014'),
          )
        ),
      ),
    ),

    /* ─── Checkout Modal ─── */
    showCheckout && !paid && React.createElement('div', {
      style: w.overlay,
      onClick: (e) => { if (e.target === e.currentTarget) setShowCheckout(false); },
    },
      React.createElement('div', { style: w.modal },
        React.createElement('h2', { style: w.modalTitle }, 'Your Decision Record'),
        React.createElement('p', { style: w.modalDesc },
          'The Walk you just completed, typeset for the file.'),
        React.createElement('p', { style: { ...w.modalDesc, fontStyle: 'italic' } },
          'One decision, one document.'),

        /* Price line */
        React.createElement('div', { style: w.priceRow },
          React.createElement('span', { style: w.priceLabel }),
          React.createElement('div', { style: { display: 'flex', alignItems: 'baseline', gap: '8px' } },
            React.createElement('span', { style: { ...w.priceAmount, textDecoration: 'line-through', color: 'var(--fg-tertiary)', fontWeight: 400, fontSize: '15px' } }, '$79'),
            React.createElement('span', { style: w.priceAmount }, '$39'),
          ),
        ),

        /* Email */
        React.createElement('input', {
          type: 'email',
          placeholder: 'Email for delivery',
          value: email,
          onChange: (e) => setEmail(e.target.value),
          style: w.modalInput,
          autoFocus: true,
        }),

        /* Card inputs (mock) */
        React.createElement('input', {
          type: 'text',
          placeholder: 'Card number',
          style: w.modalInput,
          maxLength: 19,
        }),
        React.createElement('div', { style: w.cardInputRow },
          React.createElement('input', {
            type: 'text',
            placeholder: 'MM / YY',
            style: { ...w.modalInput, flex: 1 },
            maxLength: 7,
          }),
          React.createElement('input', {
            type: 'text',
            placeholder: 'CVC',
            style: { ...w.modalInput, flex: 1 },
            maxLength: 4,
          }),
        ),

        React.createElement('button', {
          style: { ...w.modalBtn, opacity: email.includes('@') ? 1 : 0.5 },
          onClick: () => { if (email.includes('@')) { setPaid(true); } },
        }, 'Pay $39'),
        React.createElement('span', { style: w.trustLine }, 'Secure payment by Stripe.'),
        React.createElement('button', {
          style: w.modalGhost,
          onClick: () => setShowCheckout(false),
        }, 'Not now'),
      ),
    ),

    /* ─── Confirmation Modal — editorial register ─── */
    paid && showCheckout && React.createElement('div', {
      style: w.overlay,
      onClick: (e) => { if (e.target === e.currentTarget) setShowCheckout(false); },
    },
      React.createElement('div', { style: { ...w.modal, gap: 'var(--space-4)' } },
        /* Quiet em-dash mark instead of big checkmark */
        React.createElement('span', { style: {
          fontFamily: 'var(--font-serif)',
          fontSize: '24px',
          color: 'var(--color-success)',
          lineHeight: 1,
        } }, '\u2014'),
        React.createElement('h2', { style: w.modalTitle }, 'Your decision is on the record.'),
        React.createElement('div', { style: { margin: 'var(--space-2) 0' } },
          React.createElement('p', { style: {
            fontFamily: 'var(--font-serif)',
            fontSize: '17px',
            fontWeight: 500,
            color: 'var(--fg-primary)',
            margin: '0 0 4px 0',
            lineHeight: 1.3,
          } }, 'Launching a Peanut Butter Product'),
          React.createElement('span', { style: {
            fontFamily: 'var(--font-sans)',
            fontSize: '11px',
            color: 'var(--fg-tertiary)',
            letterSpacing: '0.02em',
          } }, 'Ref: DEC-2026-042'),
        ),
        React.createElement('p', { style: { ...w.modalDesc, marginTop: 'var(--space-2)' } },
          'Sent to ', React.createElement('strong', null, email || 'your email'), '. Also ready to download below.'),
        React.createElement('button', {
          style: { ...w.modalBtn, background: 'var(--accent)' },
          onClick: () => setShowCheckout(false),
        }, 'Download PDF'),
        React.createElement('button', {
          style: { ...w.modalGhost, color: 'var(--accent)' },
          onClick: () => onNavigate('walk'),
        }, 'Walk another decision \u2192'),
      ),
    ),
  );
};

window.WalkView = WalkView;
