/* global React, V2Icon */
const { useState, useEffect, useRef } = React;

function V2Composer({
  draft, onChangeText, onChangeType, onChangeSubType, onAnalyse, onExpand, onDiscard, onClose,
  noteTypes, sources, autosave,
}) {
  const textRef = useRef(null);
  const [showSources, setShowSources] = useState(true);

  useEffect(() => {
    if (textRef.current) textRef.current.focus();
  }, []);

  const isAnalysing = draft && draft.state === 'analysing';

  return (
    <aside style={{
      width: 420, flexShrink: 0,
      background: '#fff',
      borderLeft: '1px solid var(--sage-200)',
      display: 'flex', flexDirection: 'column', minHeight: 0,
    }}>
      {/* Header — brand-tinted to distinguish the compose surface from the
          (sage-toned) note view and patient-context panels. */}
      <div style={{
        padding: '10px 14px',
        borderBottom: '1px solid var(--primary)',
        background: 'var(--primary-muted)',
        display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0,
      }}>
        <V2Icon name="pencilOutline" size={13} stroke="var(--primary)" />
        <span style={{
          fontSize: 11, fontWeight: 700, letterSpacing: '0.06em',
          textTransform: 'uppercase', color: 'var(--primary)',
        }}>
          {draft?.subType
            ? `${draft.subType} ${draft.type}`
            : (draft?.type && draft.type !== 'Untitled' ? draft.type : 'New note')}
        </span>
        <span style={{ fontSize: 11, color: 'var(--primary)', opacity: 0.5 }}>·</span>
        <span style={{ fontSize: 11.5, color: 'var(--primary)', opacity: 0.85 }}>Draft</span>
        <div style={{ flex: 1 }} />
        <span style={{
          fontSize: 10.5, color: 'var(--primary)', opacity: 0.7,
          fontFamily: 'var(--font-mono)', display: 'flex', alignItems: 'center', gap: 4,
        }}>
          {autosave === 'saving' ? (
            <><span style={savingDot()} /> Saving…</>
          ) : (
            <><V2Icon name="check" size={11} stroke="var(--primary)" /> Saved</>
          )}
        </span>
        <button
          onClick={onExpand}
          aria-label="Open in editor"
          title="Open in editor"
          style={iconBtn()}
        >
          <V2Icon name="expandArrows" size={13} />
        </button>
        <button
          onClick={onClose}
          aria-label="Close composer"
          title="Close"
          style={iconBtn()}
        >
          <V2Icon name="x" size={14} />
        </button>
      </div>

      {/* Textarea */}
      <div style={{ flex: 1, padding: '12px 14px 8px 14px', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
        <textarea
          ref={textRef}
          value={draft?.sourceText || ''}
          onChange={e => onChangeText(e.target.value)}
          placeholder={draft?.typeId
            ? `Quick rough notes for the ${(draft.subType || draft.type || '').toLowerCase()}…`
            : `Just start writing… or pick a note type above to template the layout.\n\nE.g. "D3. Reasonably well o/n. No SOB/CP. Cough settling. Bloods K 6.0 — hyperK. Cancel disch."`}
          style={{
            flex: 1, minHeight: 180, resize: 'none',
            border: 0, outline: 0,
            fontSize: 13.5, lineHeight: 1.55,
            color: 'var(--sage-800)',
            fontFamily: 'var(--font-serif)',
            background: 'transparent',
            padding: '8px 4px',
          }}
        />
      </div>

      {/* Source-aware context — chat-style. Only appears once Analyse has been triggered. */}
      {(draft?.state === 'analysing' || draft?.state === 'ai_draft_ready' || draft?.state === 'user_reviewed') && (
      <div style={{
        margin: '0 14px 8px 14px',
        border: '1px solid var(--sage-200)',
        borderRadius: 8,
        background: 'var(--sage-50)',
        flexShrink: 0,
      }}>
        <button
          onClick={() => setShowSources(s => !s)}
          style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 7,
            padding: '7px 10px', border: 0, background: 'transparent',
            cursor: 'pointer', fontFamily: 'var(--font-sans)',
            color: 'var(--sage-600)',
          }}
        >
          <V2Icon name="sparkle" size={11} stroke="var(--ai)" fill="var(--ai)" />
          <span style={{
            fontSize: 10.5, fontWeight: 600,
            letterSpacing: '0.06em', textTransform: 'uppercase',
            color: 'var(--ai-text)',
          }}>Using context</span>
          <span style={{
            fontSize: 10, color: 'var(--sage-500)',
            background: '#fff', border: '1px solid var(--sage-200)',
            padding: '0 5px', borderRadius: 9999, fontFamily: 'var(--font-mono)',
          }}>{sources.length}</span>
          <div style={{ flex: 1 }} />
          <V2Icon name={showSources ? 'chevronUp' : 'chevronDown'} size={12} stroke="var(--sage-500)" />
        </button>
        {showSources && (
          <ul style={{
            listStyle: 'none', margin: 0,
            padding: '0 10px 8px 10px',
            display: 'flex', flexDirection: 'column', gap: 3,
          }}>
            {sources.map((s, i) => (
              <li key={i} style={{
                display: 'flex', alignItems: 'center', gap: 7,
                padding: '4px 6px', borderRadius: 5,
                background: '#fff', border: '1px solid var(--sage-200)',
              }}>
                <SourceIcon kind={s.kind} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    fontSize: 11.5, fontWeight: 500, color: 'var(--sage-700)',
                    whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  }}>{s.label}</div>
                  <div style={{ fontSize: 10, color: 'var(--sage-500)' }}>{s.detail}</div>
                </div>
                <button
                  aria-label="Remove source"
                  style={{
                    background: 'transparent', border: 0, padding: 2,
                    color: 'var(--sage-400)', cursor: 'pointer', display: 'flex',
                  }}
                >
                  <V2Icon name="x" size={11} />
                </button>
              </li>
            ))}
            <li style={{ marginTop: 2 }}>
              <button style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '4px 6px', border: 0, background: 'transparent',
                color: 'var(--sage-500)', cursor: 'pointer',
                fontSize: 11, fontFamily: 'var(--font-sans)',
              }}>
                <V2Icon name="attach" size={11} />
                Add context…
              </button>
            </li>
          </ul>
        )}
      </div>
      )}

      {/* Footer actions */}
      <div style={{
        padding: '10px 14px',
        borderTop: '1px solid var(--sage-200)',
        background: '#fff',
        display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0,
      }}>
        <button
          onClick={onDiscard}
          style={ghostBtn('var(--reject-text)')}
          title="Discard draft"
        >
          <V2Icon name="trash" size={12} />
          Discard
        </button>
        <div style={{ flex: 1 }} />
        <button
          onClick={onExpand}
          style={ghostBtn('var(--sage-600)')}
          title="Expand to editor"
        >
          <V2Icon name="expandArrows" size={12} />
          Expand
        </button>
        <button
          onClick={onAnalyse}
          disabled={isAnalysing || !draft?.sourceText}
          style={{
            display: 'flex', alignItems: 'center', gap: 6,
            padding: '7px 14px', borderRadius: 6,
            border: 0,
            background: isAnalysing ? 'var(--ai-surface)' : 'var(--ai)',
            color: isAnalysing ? 'var(--ai-text)' : '#fff',
            cursor: (isAnalysing || !draft?.sourceText) ? 'default' : 'pointer',
            opacity: (!draft?.sourceText && !isAnalysing) ? 0.5 : 1,
            fontSize: 12, fontWeight: 600,
            fontFamily: 'var(--font-sans)',
            letterSpacing: '0.01em',
          }}
        >
          {isAnalysing ? (
            <><span style={spinDot()} /> Analysing…</>
          ) : (
            <><V2Icon name="sparkle" size={12} /> Analyse</>
          )}
        </button>
      </div>
    </aside>
  );
}

function SourceIcon({ kind }) {
  const map = {
    note: { icon: 'doc', tone: 'var(--primary-light)', bg: 'var(--primary-muted)' },
    issues: { icon: 'alertTriangle', tone: '#d97706', bg: '#fffbeb' },
    pmhx: { icon: 'list', tone: 'var(--sage-600)', bg: 'var(--sage-100)' },
    meds: { icon: 'pill', tone: 'var(--sage-600)', bg: 'var(--sage-100)' },
    upload: { icon: 'attach', tone: 'var(--ai)', bg: 'var(--ai-surface)' },
    results: { icon: 'shield', tone: 'var(--primary-light)', bg: 'var(--primary-muted)' },
  };
  const m = map[kind] || map.note;
  return (
    <span style={{
      width: 22, height: 22, borderRadius: 5,
      background: m.bg,
      display: 'grid', placeItems: 'center', flexShrink: 0,
    }}>
      <V2Icon name={m.icon} size={11} stroke={m.tone} />
    </span>
  );
}

function iconBtn() {
  return {
    width: 26, height: 26, borderRadius: 6,
    border: 0, background: 'transparent',
    color: 'var(--sage-500)', cursor: 'pointer',
    display: 'grid', placeItems: 'center',
  };
}

function ghostBtn(color) {
  return {
    display: 'flex', alignItems: 'center', gap: 5,
    padding: '6px 10px', borderRadius: 6,
    border: '1px solid var(--sage-200)',
    background: '#fff', color, cursor: 'pointer',
    fontSize: 11.5, fontWeight: 500,
    fontFamily: 'var(--font-sans)',
  };
}

function savingDot() {
  return {
    width: 7, height: 7, borderRadius: '50%',
    background: 'var(--flag)', display: 'inline-block',
    animation: 'pulse 1.2s ease-in-out infinite',
  };
}

function spinDot() {
  return {
    width: 10, height: 10, borderRadius: '50%',
    border: '2px solid var(--ai-border)',
    borderTopColor: 'var(--ai)',
    display: 'inline-block',
    animation: 'spin 0.8s linear infinite',
  };
}

window.V2Composer = V2Composer;
