// MFM Chat — Prompt Input (the most distinctive composition).
// Matches components/multimodal-input.tsx + components/elements/prompt-input.tsx.

const CHAT_MODELS = [
  {
    id: "chat-model",
    name: "Grok Vision",
    description: "Advanced multimodal model with vision and text capabilities",
  },
  {
    id: "chat-model-reasoning",
    name: "Grok Reasoning",
    description: "Uses advanced chain-of-thought reasoning for complex problems",
  },
];

const ModelSelectorCompact = ({ value, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const current = CHAT_MODELS.find((m) => m.id === value);
  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="inline-flex h-8 items-center gap-1 rounded-md px-2 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
      >
        <CpuIcon size={16} />
        <span className="hidden sm:block text-xs font-medium">
          {current?.name}
        </span>
        <ChevronDownIcon size={16} />
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          <div className="absolute bottom-full left-0 z-50 mb-1 min-w-[260px] rounded-md border border-border bg-popover p-0 shadow-md">
            <div className="flex flex-col gap-px">
              {CHAT_MODELS.map((m) => (
                <button
                  key={m.id}
                  type="button"
                  onClick={() => {
                    onChange(m.id);
                    setOpen(false);
                  }}
                  className="flex items-start gap-2 px-2 py-1.5 text-left hover:bg-accent rounded-sm"
                >
                  <div className="flex-1">
                    <div className="truncate text-xs font-medium">{m.name}</div>
                    <div className="mt-px truncate text-[10px] text-muted-foreground leading-tight">
                      {m.description}
                    </div>
                  </div>
                  {value === m.id && (
                    <span className="mt-0.5"><CheckCircleFillIcon size={12} /></span>
                  )}
                </button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

const AttachmentChip = ({ name, isUploading, onRemove }) => (
  <div className="relative flex items-center gap-2 rounded-md border border-border bg-background px-2 py-1 pr-7 text-xs">
    {isUploading ? (
      <span className="inline-block h-3 w-3 animate-spin rounded-full border-2 border-muted-foreground border-t-transparent" />
    ) : (
      <PaperclipIcon size={12} />
    )}
    <span className="max-w-[120px] truncate">{name}</span>
    {!isUploading && onRemove && (
      <button
        type="button"
        onClick={onRemove}
        className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex h-4 w-4 items-center justify-center rounded-sm hover:bg-accent"
        aria-label="Remove"
      >
        <CrossSmallIcon size={10} />
      </button>
    )}
  </div>
);

// Inline "context" usage meter on the right of the textarea.
const ContextMeter = ({ used, total }) => {
  const pct = Math.min(100, Math.round((used / total) * 100));
  // a tiny circular progress, matches the visual weight of components/elements/context.tsx
  const r = 6;
  const c = 2 * Math.PI * r;
  return (
    <div className="ml-2 mt-1 flex items-center gap-1 text-[10px] text-muted-foreground whitespace-nowrap">
      <svg width="16" height="16" viewBox="0 0 16 16">
        <circle cx="8" cy="8" r={r} stroke="var(--border)" strokeWidth="1.5" fill="none" />
        <circle
          cx="8" cy="8" r={r}
          stroke="currentColor" strokeWidth="1.5" fill="none"
          strokeDasharray={c}
          strokeDashoffset={c * (1 - pct / 100)}
          transform="rotate(-90 8 8)"
        />
      </svg>
      <span>{pct}%</span>
    </div>
  );
};

const PromptInput = ({
  input,
  setInput,
  onSubmit,
  onStop,
  status, // "ready" | "submitted" | "streaming" | "error"
  selectedModelId,
  onModelChange,
  attachments,
  setAttachments,
  uploadFile,
}) => {
  const fileRef = React.useRef(null);
  const textareaRef = React.useRef(null);
  const isStreaming = status === "streaming" || status === "submitted";
  const canSubmit = input.trim().length > 0 && status === "ready";

  const handleFile = async (e) => {
    const files = Array.from(e.target.files || []);
    for (const f of files) {
      // queue placeholder
      const placeholder = {
        url: "", name: f.name, contentType: f.type, _uploading: true,
      };
      setAttachments((curr) => [...curr, placeholder]);
      // fake upload
      const result = await uploadFile(f);
      setAttachments((curr) =>
        curr.map((a) => (a === placeholder ? { ...result, _uploading: false } : a))
      );
    }
    if (fileRef.current) fileRef.current.value = "";
  };

  return (
    <form
      className="rounded-xl border border-border bg-background p-3 shadow-xs transition-all duration-200 focus-within:border-border hover:border-muted-foreground/50"
      onSubmit={(e) => {
        e.preventDefault();
        if (canSubmit) onSubmit();
      }}
    >
      {attachments.length > 0 && (
        <div className="mb-1 flex flex-row items-end gap-2 overflow-x-auto pb-1">
          {attachments.map((a, i) => (
            <AttachmentChip
              key={i}
              name={a.name}
              isUploading={a._uploading}
              onRemove={() =>
                setAttachments((curr) => curr.filter((x) => x !== a))
              }
            />
          ))}
        </div>
      )}

      <div className="flex flex-row items-start gap-1 sm:gap-2">
        <textarea
          ref={textareaRef}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && !e.shiftKey) {
              e.preventDefault();
              if (canSubmit) onSubmit();
            }
          }}
          rows={3}
          placeholder="Send a message..."
          className="grow resize-none bg-transparent p-2 text-sm placeholder:text-muted-foreground focus:outline-none"
          style={{ minHeight: 84 }}
        />
        <ContextMeter used={1240} total={32000} />
      </div>

      <div className="flex items-center justify-between p-0">
        <div className="flex items-center gap-0.5 sm:gap-1">
          <input
            ref={fileRef}
            type="file"
            multiple
            className="hidden"
            onChange={handleFile}
          />
          <Tooltip label="Attach files" side="top">
            <button
              type="button"
              onClick={() => fileRef.current?.click()}
              disabled={selectedModelId === "chat-model-reasoning"}
              className="aspect-square h-8 rounded-lg p-1 inline-flex items-center justify-center text-muted-foreground hover:bg-accent disabled:opacity-40 disabled:hover:bg-transparent transition-colors"
              aria-label="Attach"
            >
              <PaperclipIcon size={14} />
            </button>
          </Tooltip>
        </div>

        <div className="flex items-center gap-2">
          <ModelSelectorCompact value={selectedModelId} onChange={onModelChange} />
          {isStreaming ? (
            <button
              type="button"
              onClick={onStop}
              className="size-8 rounded-full bg-foreground p-1 inline-flex items-center justify-center text-background hover:opacity-90 transition-colors"
              aria-label="Stop"
            >
              <StopIcon size={12} />
            </button>
          ) : (
            <button
              type="submit"
              disabled={!canSubmit}
              className="btn-fill-hover size-8 rounded-full bg-primary inline-flex items-center justify-center text-primary-foreground disabled:bg-muted disabled:text-muted-foreground transition-colors"
              aria-label="Send"
            >
              <span><ArrowUpIcon size={14} /></span>
            </button>
          )}
        </div>
      </div>
    </form>
  );
};

Object.assign(window, { PromptInput, ModelSelectorCompact, CHAT_MODELS });
