"use client";

import { useState } from "react";

function normalizeHex(value: string, fallback: string) {
  return /^#[0-9A-Fa-f]{6}$/.test(value) ? value : fallback;
}

export function BrandColorField({
  name,
  label,
  value,
  hint,
}: {
  name: string;
  label: string;
  value: string;
  hint?: string;
}) {
  const fallback = normalizeHex(value, "#C5FF00");
  const [text, setText] = useState(value || fallback);
  const pickerValue = normalizeHex(text, fallback);

  return (
    <div>
      <label className="label" htmlFor={`brand-${name}`}>
        {label}
      </label>
      <div className="flex items-center gap-2">
        <input
          type="color"
          value={pickerValue}
          aria-label={label}
          className="h-10 w-12 cursor-pointer rounded border border-white/10 bg-transparent p-1"
          onChange={(e) => setText(e.target.value)}
        />
        <input
          id={`brand-${name}`}
          className="input flex-1 font-mono text-sm"
          name={name}
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="#000000"
        />
      </div>
      {hint ? <p className="mt-1 text-xs text-white/40">{hint}</p> : null}
    </div>
  );
}
