import { useEditMode } from "./EditModeContext";
import "./TrailHeader.css";

type Props = {
  title: string;
  description: string;
};

export function TrailHeader({ title, description }: Props) {
  const editContext = useEditMode();
  const isEditing = !!editContext;
  const trail = editContext?.trail;
  const updateTrail = editContext?.updateTrail;

  const displayTitle = trail?.title ?? title ?? "";
  const displayDescription = trail?.description ?? description ?? "";

  const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (updateTrail) updateTrail({ title: e.target.value });
  };

  const handleDescriptionChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (updateTrail) updateTrail({ description: e.target.value });
  };

  return (
    <div className="TrailHeader">
      {isEditing ? (
        <>
          <input
            value={displayTitle}
            onChange={handleTitleChange}
            className="TrailHeader-titleEdit"
            placeholder="name your trail"
          />
          <input
            value={displayDescription}
            onChange={handleDescriptionChange}
            className="TrailHeader-descriptionEdit"
            placeholder="describe it in a few words"
          />
        </>
      ) : (
        <>
          {displayTitle && (
            <h2 className="TrailHeader-title">
              <span>{displayTitle}</span>
            </h2>
          )}
          {displayDescription && (
            <p className="TrailHeader-description">
              <span>{displayDescription}</span>
            </p>
          )}
        </>
      )}
    </div>
  );
}
